Image size before is in DOM

后端 未结 2 840
花落未央
花落未央 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:31

    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 讨论(0)
  • 2020-12-30 07:40

    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.

    0 讨论(0)
提交回复
热议问题