jQuery .width() 在 Chrome 和 Safari 上的问题

13

我在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;    
}

请看这个SO问题。我认为你们的问题是一样的。 - lonesomeday
1个回答

37

document.ready事件中,可能会加载或不加载图像。如果它们不在缓存中,则它们很可能没有被加载。相反,当图像已加载时,请使用window.onload事件,像这样:

var total=0; 
$(window).load(function() {
  $('.thumb').each(function() {
    total += $(this).width();
  });
});

1
width()也没有给我正确的值,如何解决?http://stackoverflow.com/questions/18650991/phantom-height-when-specifying-the-width-of-a-li-using-jquery - mrN

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接