在jQuery中获取图像的原始宽度和高度
我需要在给定特定来源的情况下获得图像的原始宽度和高度。 我目前的方法是:
img.tag = ""; img.Owidth = 0; img.Oheight = 0; $(img.tag).load(function() { img.Owidth = $(this).width(); img.Oheight = $(this).height(); }).appendTo(img.parent());
Owidth
和Oheight
是加载图像的原始尺寸。 我想知道是否有更好的方法来做到这一点:
- 图像可能已加载,但显示的尺寸与原始尺寸不同。
- 图像尚未加载
跨浏览器:
jsFiddle演示
$("").load(function(){ var width = this.width, height = this.height; alert( 'W='+ width +' H='+ height); }).attr("src", "image.jpg");
HTMLImageElement属性/ HTML5兼容的浏览器
如果要调查所有HTMLImageElement 属性 : https : //developer.mozilla.org/en/docs/Web/API/HTMLImageElement
许多这些属性已经在现代的HTML5兼容浏览器中可用,并且可以使用jQuery的.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 ... );
对于Chrome和Firefox(很快就会推荐IE),您可以使用……
var width = $('img').prop('naturalWidth'); var height = $('img').prop('naturalHeight');