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。这段代码有什么问题?
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);
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
试试这个:
Try this:
我使用这种方式:
这是我找到的唯一可行的解决方案。
I used this way:
And it was the only working solution I have found.
我发现最好的方法是让计算机先进行缩放。
并在主体中声明 onload = "some_function()" 。
然后在脚本中获取尺寸。
我注意到使用 google chrome,您需要确保在 body div 中调用 onload="function",否则图像值不会设置,并且它会拉入 0px 的宽度和高度。
I found the best way is to let the computer do the scaling first.
and declaring the onload = "some_function()" in the body.
and then getting the sizing afterward in the script.
I noticed with google chrome you need to make sure you call the onload="function" within the body div otherwise the image values arn't set and it pulls in 0px for width and height.
这是没有意义的:
您想要将实际函数传递给事件:
并在函数中使用
this
而不是img
。此外,您还需要在更改图像的 src 属性之前分配事件。
另请注意,图像上的加载事件存在许多问题。来自 关于 load() 的 jQuery 手册:
This makes no sense:
you want to pass the actual function to the event:
and use
this
instead ofimg
within the function.Also you need to assign the event before changing the image's
src
property.Also note that there are numerous problems with the load event on images. From the jQuery manual on load():