2011-07-11 23 views
0

假設我在下面列出了這個列表。每張圖片都有不同的寬度,a標籤的右邊距爲15px,這樣可以將列表項稍微擴展一些,以便爲下一張圖片留出一定的空間。如何計算寬度變化範圍內的單個li的寬度

<div id="otherproducts"> 
    <ul> 
    <li><a href="products/sign-materials/"><img border="0" src="assets/images/subbrands/slider/slider.png" alt="" /></a></li> 
    <li><a href="products/sign-materials/"><img border="0" src="assets/images/subbrands/slider/alight-slider.png" alt="" /></a></li> 
    <li><a href="products/sign-materials/"><img border="0" src="assets/images/subbrands/slider/eclider.png" alt="" /></a></li> 
    <li><a href="products/sign-materials/"><img border="0" src="assets/images/subbrands/slider/aluer.png" alt="" /></a></li> 
    <li><a href="products/sign-materials/"><img border="0" src="assets/images/subbrands/slider/alucr.png" alt="" /></a></li> 
    </ul> 
</div> 

我怎樣才能jQuery來給我的項目的正確寬度在我的計算如下這樣我就可以給UL正確的總寬度,因爲目前總的是走出來比它應該更大...

var obj = $(this);    
var s = $("li", obj).length; 
var w = $("li", obj).width(); 
var h = $("li", obj).height(); 
obj.width(w); 
obj.height(h); 
$("ul", obj).css('width',s*w); 

回答

0
var ul= jQuery('ul'), 
    finalWidth=0,finalHeight=0; 

ul.find('li').each(function(){ 
    finalWidth+=jQuery(this).width(); 
    finalHeight+=jQuery(this).height(); 
}); 


ul.height(finalHeight).width(finalWidth); 
+0

:你用'jqeury'insted'$'? – K6t

1

您的解決方案只測量第一個項目,然後假設每個項目是長。相反遍歷所有項目,分別測量它們,使用jQuery的每個:

嘗試

var width = 0; 
$("li", obj).each(function(){width += $(this).width()}); 

$("ul", obj).width(width); 
0

到斯特芬·穆勒的做法類似,您可能需要使用.each(),但你應該使用.outerWidth(true)功能拿起保證金也是如此。

編輯:更新我的代碼,以便它可以代替你的代碼。

var obj = $(this); 
// calculate the max height of the <li>s 
var max_h = 0; 
$("li", obj).each(function() { 
    max_h = Math.max(max, $(this).outerHeight(true)); // include padding and margins 
}); 
obj.height(max_h); // set the (presumedly <div>'s) height to the max_height 
var w = 0; 
$("li", obj).each(function() { 
    w += $(this).outerWidth(true); 
}); 
$("ul", obj).width(w); // set the width of the <ul> to be the sum of the <li>'s widths 
+0

你能告訴我這可以包含在我的代碼中嗎? – Andy

+0

我編輯了我的答案來匹配。讓我知道你如何繼續使用新的代碼。 – GregL