如何使用jQuery获取实际图像宽度和高度?

X10*_*0nD 19 jquery image

在页面上,我显示了100个图像,其中宽度和高度属性已更改.图像ID处于循环中.

如何在此循环中获取原始图像大小?

$(this).appendTo(".prod_image").attr('height',150).attr('width',150).attr('title','').attr('name','').attr('alt','').attr('id','id'+i);
Run Code Online (Sandbox Code Playgroud)

小智 34

您可以使用dom对象的naturalWidth和naturalHeight属性检索图像的原始尺寸.

例如.

var image = document.getElementById('someImage');

var originalWidth = image.naturalWidth; 
var originalHeight = image.naturalHeight;
Run Code Online (Sandbox Code Playgroud)

使用jQuery看起来像:

var image = $('#someImage');

var originalWidth = image[0].naturalWidth; 
var originalHeight = image[0].naturalHeight;
Run Code Online (Sandbox Code Playgroud)

  • +1强有力的注意,IE 8及更低版本不支持此功能(因此旧浏览器需要额外的回退). (7认同)

Vov*_*pov 21

HTML:

  <img id="myimg" src="http://azart-cash.ru/big_pics/kazino_AzartPlay.png"
  width="120" height="140"/>
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

var img = new Image();
img.onload = function() {
  alert(this.width + 'x' + this.height);
}
img.src = $("#myimg").attr('src');
Run Code Online (Sandbox Code Playgroud)

或者只是在这里查看http://jsfiddle.net/Increazon/A5QJM/1/


Eri*_*rik 6

获得原始大小的唯一方法是将其恢复到原始状态.您可以通过克隆图像,然后删除高度和宽度属性来获得真实值,从而轻松完成此操作.您还必须将更改的图像插入页面,否则它不会有计算的高度/宽度.您可以在屏幕外的div中轻松完成此操作.这是一个例子:

http://jsbin.com/ocoto/edit

JS:

// Copy the image, and insert it in an offscreen DIV
aimgcopy = $('#myimg').clone();
$('#store').append(aimgcopy);

// Remove the height and width attributes
aimgcopy.removeAttr('height');
aimgcopy.removeAttr('width');

// Now the image copy has its "original" height and width
alert('Height: '+aimgcopy.height()+' Width: '+aimgcopy.width());
Run Code Online (Sandbox Code Playgroud)

CSS:

  #store {  position: absolute;  left: -5000px; }
Run Code Online (Sandbox Code Playgroud)

HTML:

  <img id="myimg" src="http://sstatic.net/so/img/logo.png" width="300" height="120"/>
  <div id="store"></div>
Run Code Online (Sandbox Code Playgroud)