开发者

Image size before is in DOM

开发者 https://www.devze.com 2023-03-08 12:11 出处:网络
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());

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());
$(imgLo开发者_Python百科ad).unbind("load");
$(imgLoad).bind("load", function () {

   // Get image sizes
   alert(imgLoad.width()); // RETURN 0

});


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);

});

Working demo: http://jsfiddle.net/7twNk/

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.

Note that you do not need to keep wrapping imgLoad with $() because it is already a jQuery object.


When creating a new Image, .width will give you the native dimensions of the un-rendered image, whereas .width() is a jQuery method, and doesn't return a value until the image is inserted into the DOM.

In plain old JS;

var i = new Image()
i.src = 'blah.gif'
var h = i.height
var w = i.width

will return you a true value

0

精彩评论

暂无评论...
验证码 换一张
取 消