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

后端 未结 30 2384
傲寒
傲寒 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:27

    You can use the naturalWidth and naturalHeight properties of the HTML image element. (Here's more info).

    You would use it like this:

    //you need a reference to the DOM element, not a jQuery object. It would be better if you can use document.getElementByTagsName or ID or any other native method
    var pic = $("img")[0];
    var pic_real_width = pic.naturalWidth;
    var pic_real_height = pic.naturalHeight;
    

    It seems like this works in all browsers except on IE from version 8 and below.

提交回复
热议问题