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

23

我需要读取每个图像的自然高度并进行计算。但是,我在读取自然高度时遇到了一些问题。

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

在控制台日志中出现:(图片数量) undefined。如何读取每个图像的原始高度?

2个回答

33

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


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

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

我也尝试了这个,但对我来说也不起作用。返回“未定义”。 - David Rhoderick
1
@ArtlyticalMedia 你应该使用 load。因为如果图片没有加载完成,可能会返回 "undefined"。 - Wallace Vizerra

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

这种方法在Internet Explorer 8及以下版本中无法使用,因为它不支持' naturalWidth '和' naturalHeight '属性。要实现相同的效果,请使用以下代码:

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

1
这个不起作用。我已经在Chrome中尝试过了,可以看到源代码是正确的;我将其设置为新图像的src属性,但naturalHeight/naturalWidth却是“未定义”。 - David Rhoderick

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接