Image size before is in DOM

后端 未结 2 856
花落未央
花落未央 2020-12-30 07:02

How can I get image size before I put it into the DOM?

var imgLoad = $(\"\");
$(imgLoad).attr(\"src\", ImageGallery.ImagesList[index] + \"?\" +          


        
2条回答
  •  我在风中等你
    2020-12-30 07:40

    Use imgLoad[0].width and imgLoad[0].height instead, or use this instead of imgLoad:

    var imgLoad = $("");
    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.

提交回复
热议问题