2011-06-07 20 views
1

我遇到了jQuery代碼的問題。jQuery each()圖片寬度

事實上,我想在一行中添加每個圖像的每個寬度。所以我想這將與jquery each()函數解決,但我不知道如何。

我已經知道我是如何得到一個圖像的寬度,但我不能完成它們中的每一個。

所以,我的第一步是選擇我想要的每個圖像。這工作正常,但現在每一次嘗試都失敗了。 :(

images.each(function(i){ 
    $(images).load(function(){ 
     totalImageWidth = totalImageWidth + this.width; 
    }); 
}); 

請幫助我。

在此先感謝。

回答

3
var totalImageWidth = 0;  
images.each(function(index, item){ 
    totalImageWidth += item.width; 
}); 

嘗試的是,使用item(具有參照個體圖像)

此代碼是假設它被封裝在一個(等待頁面在執行之前被加載)。

+0

隨着使用負載雖然這裏,他就不能使用這個變量後,立即每個。 – 2011-06-07 15:12:46

+0

@kingjiv,你是什麼意思? – Neal 2011-06-07 15:13:54

+0

'$(item).load('給圖片的加載事件增加一個事件處理程序,這會稍後觸發 – 2011-06-07 15:14:49

1

嘗試以下操作:

var totalImagesWidth = 0; 
$("img").each(function() { 
    totalImagesWidth += $(this).width(); 
}); 
alert(totalImagesWidth); 

演示:http://jsfiddle.net/pkCxL/

0

我希望這可以幫助....我用這個來創建一個類似於谷歌與截圖容器發揮移動Web應用程序滾動能夠垂直。

這將是HTML:

<div id="img_container"> 
    <img src="" /> 
    <img src="" /> 
    ... 
</div> 

,這是jQuery代碼:

//use window.load to work with all browsers 
//with document.ready its not working in chrome and safari 
$(window).load(function() { 
    var img_width = 20; //start with a specific data, usually 0 
    $('#img_container').find('img').each(function() { 
     //for each img add the width plus a specific value, in this case 20 
     img_width += $(this).width() + 20; 
    }); 
    //if you need the container to have the right width to fit all the images 
    $('#img_container').css('width', img_width); 
});