【发布时间】:2014-02-17 07:02:58
【问题描述】:
我必须读取每张图片的自然高度并进行计算。但是我在读取到自然高度时遇到了一些问题。
$('div.imgkirp img').each(function(){
console.log($(this).naturalHeight);
});
它在控制台日志中得到:(图像编号)未定义。如何读取每个图像的自然高度?
【问题讨论】:
标签: javascript jquery image
我必须读取每张图片的自然高度并进行计算。但是我在读取到自然高度时遇到了一些问题。
$('div.imgkirp img').each(function(){
console.log($(this).naturalHeight);
});
它在控制台日志中得到:(图像编号)未定义。如何读取每个图像的自然高度?
【问题讨论】:
标签: javascript jquery image
尝试使用图片的属性naturalHeight,使用jQuery的prop方法
$('div.imgkirp img').each(function(){
console.log($(this).prop('naturalHeight'));
});
【讨论】:
load。因为如果图片没有加载,可能会返回“undefined”。
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);
};
【讨论】: