使用jquery获取图像宽度和高度

我有一个非常简单的代码,烦人的工作和我的生活,我不明白为什么它现在失败:

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'); } 

好的 – 当我在jsFiddle上测试它时,我给出的上一个答案是无效的 – 我创建了这个,它可以做你想要的吗? 你需要有“新形象()”部分吗? http://jsfiddle.net/R89Qr/3/ – 给图像一些硬编码的尺寸……

我稍微改变了你的代码,所以它做到了这一点:

  function imageSize(img){ var theImage = new Image(); // ignoring this part when checking the image width/height theImage.src = img.attr('src'); var imgwidth = $(img).width(); var imgheight = $(img).height(); alert(imgwidth+'-'+imgheight); } $('img').each(function(){ var imgsrc = jQuery(this); imageSize(imgsrc); }); 

您必须等待,直到您的图像将被加载,然后访问其大小:

 function imageSize(img){ var theImage = new Image(); theImage.onload = function(){ var imgwidth = theImage.width; var imgheight = theImage.height; alert(imgwidth+'-'+imgheight); } theImage.src = img.attr('src'); }