之前的图片大小在DOM中 [英] Image size before is in DOM
本文介绍了之前的图片大小在DOM中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在将图像放入DOM之前如何获得图像大小?
How can I get image size before I put it into the DOM?
var imgLoad = $("<img />");
$(imgLoad).attr("src", ImageGallery.ImagesList[index] + "?" + new Date().getTime());
$(imgLoad).unbind("load");
$(imgLoad).bind("load", function () {
// Get image sizes
alert(imgLoad.width()); // RETURN 0
});
推荐答案
使用imgLoad[0].width
和imgLoad[0].height
代替,或者使用this
代替imgLoad
:
Use imgLoad[0].width
and imgLoad[0].height
instead, or use this
instead of imgLoad
:
var imgLoad = $("<img />");
imgLoad.attr("src", ImageGallery.ImagesList[index] + "?" + new Date().getTime());
imgLoad.unbind("load");
imgLoad.bind("load", function () {
// Get image sizes
alert(this.width);
});
之所以起作用,是因为浏览器在下载图像时会填充元素的height
/width
属性.另一方面,jQuery会获取元素的实际可见尺寸—.不显示元素时始终为0.
This works because the browser populates the height
/width
properties of the element when it downloads the image. jQuery, on the other hand, fetches the actual visible dimensions of the element — this will always be 0 when an element isn't displayed.
请注意,您不必将imgLoad
与$()
换行,因为它已经是jQuery对象.
Note that you do not need to keep wrapping imgLoad
with $()
because it is already a jQuery object.
这篇关于之前的图片大小在DOM中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文