我已经在css中将图像的高度设置为某个值,并且宽度会自动修改以保持纵横比。我正在使用.width()jquery函数在css调整图像大小后获取图像的宽度。在Firefox和Internet Explorer中,这很有效,但在chrome和safari中,每个图像返回的宽度始终为0。我正在使用的代码如下:
var total=0;
var widthdiv=0;
$(function(){
$('.thumb').each(function(){
widthdiv=$(this).width();
total+=widthdiv;
alert(widthdiv); //added so i can see what value is returned.
});
});
和图像的CSS:
#poze img{
height:80px;
width:auto;
border:0px;
padding-right:4px;
}
答案 0 :(得分:37)
在document.ready
(您当前正在使用)中,可能会加载也可能不会加载图像,如果它们不在缓存中,则可能未加载。而是在加载图像 时使用window.onload
event,如下所示:
var total=0;
$(window).load(function() {
$('.thumb').each(function() {
total += $(this).width();
});
});