载入图片后,Javascript计算图片大小 [英] Javascript calculate image size, after image load

查看:187
本文介绍了载入图片后,Javascript计算图片大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function loader(img) {
        var imgH = img.height;
        var imgW = img.width;
        console.log(imgH, imgW);    
    };

img = new Image();
img.src ='../images/pic1.jpeg';
img.onLoad = loader(img);

如此,我将得到图像的大小,但是在控制台中却得到了"0 0",这是有道理的.图像大小为500X700.这段代码有什么问题?

So, It is exepeted, that I'll get image's size, but I got "0 0" in console. And size of image is 500X700. What's wrong with this code?

推荐答案

这没有道理:

img.onLoad = loader(img);

您要将实际功能传递给事件:

you want to pass the actual function to the event:

img.onload = loader;

,然后在函数中使用this代替img.

and use this instead of img within the function.

此外,您还需要在更改图像的src属性之前,先分配事件.

Also you need to assign the event before changing the image's src property.

还请注意,图像上的load事件存在许多问题.摘自有关load()的jQuery手册:

Also note that there are numerous problems with the load event on images. From the jQuery manual on load():

与图片一起使用时的加载事件提示

Caveats of the load event when used with images

开发人员试图使用.load()快捷方式解决的一个常见挑战是,在完全加载图像(或图像集合)后执行函数.有几个已知的注意事项,应该注意.这些是:

A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:

  • 它不能始终如一地工作,也不能可靠地跨浏览器
  • 如果图像src设置为与以前相同的src,则无法在WebKit中正确触发
  • 它不能正确地使DOM树冒泡
  • It doesn't work consistently nor reliably cross-browser
  • It doesn't fire correctly in WebKit if the image src is set to the same src as before
  • It doesn't correctly bubble up the DOM tree

这篇关于载入图片后,Javascript计算图片大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆