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);
所以,它是 exepeted,我将获得图像的大小,但我在控制台中得到“0 0”。图像大小为 500X700。这段代码有什么问题?
最佳答案
这是没有意义的:
img.onLoad = loader(img);
您想将实际函数传递给事件:
img.onload = loader;
并在函数中使用 this
而不是 img
。
此外,您还需要在 更改图像的 src
属性之前分配事件。
另请注意,图像上的加载事件存在许多问题。来自jQuery manual on load():
Caveats of the load event when used with images
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:
- 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计算图像大小,图像加载后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7267663/