在jQuery中获取图像的原始宽度和高度

Joe*_*oey 9 jquery image preloading

我需要在给定特定来源的情况下获得图像的原始宽度和高度.我目前的方法是:

img.tag = "<img style='display:none;' src='" + img.src + "' />";
img.Owidth = 0;
img.Oheight = 0;

$(img.tag).load(function() {
    img.Owidth = $(this).width();
    img.Oheight = $(this).height();
}).appendTo(img.parent());
Run Code Online (Sandbox Code Playgroud)

使用OwidthOheight成为加载图像的原始尺寸.我想知道是否有更好的方法来做到这一点:

  • 图像可能已加载,但显示的尺寸与原始尺寸不同.
  • 图像尚未加载

Rok*_*jan 13

跨浏览器:

jsFiddle演示

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

HTMLImageElement属性/ HTML5兼容的浏览器

如果要调查所有HTMLImageElement 属性:https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement
许多这些属性已经在现代的HTML5兼容浏览器中可用,并且可以使用jQuery的metod访问.prop()

jsFiddle演示

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 ... 
);
Run Code Online (Sandbox Code Playgroud)


ale*_*lex 13

对于Chrome和Firefox(很快就会推荐IE),您可以使用......

var width = $('img').prop('naturalWidth');
var height = $('img').prop('naturalHeight');
Run Code Online (Sandbox Code Playgroud)