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

时间:2014-01-26 13:25:12

标签: javascript jquery image

我必须阅读每个图像的自然高度,我应该进行计算。但是我读到自然高度时遇到了一些问题。

$('div.imgkirp img').each(function(){
    console.log($(this).naturalHeight);
});

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

2 个答案:

答案 0 :(得分:29)

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

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

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

答案 1 :(得分:26)

尝试使用naturalHeight

prop方法使用图片的属性jQuery
$('div.imgkirp img').each(function(){

   console.log($(this).prop('naturalHeight'));
});