2011-11-14 42 views
3

我jQuery代码:jQuery的获取图像的宽度

img[i]='img-src'; 
$("#popimage1").attr("src",img[i]); 
alert($("#popimage1").width());  //doesn't give the width of the current image, but it gives for the previous, and for first null 

我的html代码:

<img src="" id="popimage1"/> 

等等概念是我我加载不同的图片src为每个使用jQuery,然后我做一些宽度和高度的计算。问题是我得到的图像值与前一个计数器i。我做了一个临时的解决方案,通过把

$("#popimage1").hide(); 
    setTimeout(alert($("#popimage1").width(),2000); 
    $("#popimage1").show(); 

但它不总是工作,并导致不必要的超时。 而不是警报有另一个使用img宽度和高度的函数,我只是为了方便而写了alert。任何帮助感谢!

+0

可能重复[获取真实图像的宽度和高度的JavaScript在Safari /铬?](http://stackoverflow.com/questions/318630/get-real-image -width-and-height-with-javascript-in-safari-chrome) – Blazemonger

+0

不是真的,我读过它.. – user666

+0

你有没有尝试过使用那里的答案?它应该为你的目的服务。 – Blazemonger

回答

9

您必须先等待图像加载。

试试这个。

img[i] = "img-src"; 
$("#popimage1").attr("src", img[i]).load(function() { 
    alert($("#popimage1").width()); 
}); 
+0

感谢这工作!我会检查load()我自己! – user666

+0

谢谢!节省了我的时间 – Shide

1

修改图像源是异步的,因此不会立即返回。

尝试处理的load()

$("#popimage1").load(function() { 
    alert($(this).width()); 
}); 
+0

谢谢你,这是一个正确的答案.. – user666

+0

@greek_no_money欢迎您。 –