Getting an image's original width and height in jQuery

China☆狼群 提交于 2019-12-05 02:51:01

Cross-Browser:

jsFiddle demo

$("<img/>").load(function(){
    var width  = this.width,
        height = this.height; 
    alert( 'W='+ width +' H='+ height);
}).attr("src", "image.jpg");

HTMLImageElement properties / HTML5 compliant browsers

If you want to investigate about all the HTMLImageElement properties: https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement
Many of those properties are available already in modern, HTML5 compliant browsers, and accessible using jQuery's .prop() metod

jsFiddle demo

var $img = $("#myImage");

console.log(
    $img.prop("naturalWidth") +'\n'+  // Width  (Natural)
    $img.prop("naturalHeight") +'\n'+ // Height (Natural)
    $img.prop("width") +'\n'+         // Width  (Rendered)
    $img.prop("height") +'\n'+        // Height (Rendered)
    $img.prop("x") +'\n'+             // X offset
    $img.prop("y")                    // Y offset ... 
);

For Chrome and Firefox (and hopefully IE soon), you can use...

var width = $('img').prop('naturalWidth');
var height = $('img').prop('naturalHeight');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!