使用jQuery获取每个图像的自然高度

Ayr*_*yro 21 javascript jquery image

我必须阅读每个图像的自然高度,我应该进行计算.但是我对自然高度的读取有一些问题.

$('div.imgkirp img').each(function(){
    console.log($(this).naturalHeight);
});
Run Code Online (Sandbox Code Playgroud)

它得到:(图像编号)在控制台日志中未定义.我如何阅读每个图像的自然高度?

Roh*_*han 30

var image = new Image();
image.src = $(this).attr("src");
alert('width: ' + image.naturalWidth + ' and height: ' + image.naturalHeight);
Run Code Online (Sandbox Code Playgroud)

此方法在IE 8及更低版本中不起作用,因为它不支持'naturalWidth'和'naturalHeight'属性.要实现相同的使用此代码

var image = new Image();
image.src = $(this).attr("src");
image.onload = function() {
console.log('height: ' + this.height);
};
Run Code Online (Sandbox Code Playgroud)


Wal*_*ers 27

尝试使用naturalHeight图像的属性,使用的prop方法jQuery

$('div.imgkirp img').each(function(){

   console.log($(this).prop('naturalHeight'));
});
Run Code Online (Sandbox Code Playgroud)