我有一个非常简单的代码,它很烦人,而且对于我一生来说,我不明白为什么现在失败了:
function imageSize(img){
var theImage = new Image();
theImage.src = img.attr('src');
var imgwidth = theImage.width;
var imgheight = theImage.height;
alert(imgwidth+'-'+imgheight);
}
传递的“ img”变量是img对象,该对象从以下位置获取:
jQuery('img')
.each(function(){
var imgsrc = jQuery(this);
imageSize(imgsrc);
});
最佳答案
该图像可能尚未加载。因此,尝试(未试用):
function imageSize(img){
var theImage = new Image();
$(theImage).load(function() {
var imgwidth = this.width;
var imgheight = this.height;
alert(imgwidth+'-'+imgheight);
});
theImage.src = img.attr('src');
}