Get the real width and height of an image with JavaScript? (in Safari/Chrome)

后端 未结 30 2226
傲寒
傲寒 2020-11-22 01:16

I am creating a jQuery plugin.

How do I get the real image width and height with Javascript in Safari?

The following works with Firefox 3, IE7 and Opera 9:

30条回答
  •  有刺的猬
    2020-11-22 01:38

    Webkit browsers set the height and width property after the image is loaded. Instead of using timeouts, I'd recommend using an image's onload event. Here's a quick example:

    var img = $("img")[0]; // Get my img elem
    var pic_real_width, pic_real_height;
    $("") // Make in memory copy of image to avoid css issues
        .attr("src", $(img).attr("src"))
        .load(function() {
            pic_real_width = this.width;   // Note: $(this).width() will not
            pic_real_height = this.height; // work for in memory images.
        });
    

    To avoid any of the effects CSS might have on the image's dimensions, the code above makes an in memory copy of the image. This is a very clever solution suggested by FDisk.

    You can also use the naturalHeight and naturalWidth HTML5 attributes.

提交回复
热议问题