2012-04-27 68 views
2

我有一個列表如下:的jQuery即使身高抹灰李的

<ul id="list"> 
    <li>lorem</li> 
    <li>lorem</li> 
    <li class="last">lorem</li> 
    <li>lorem</li> 
    <li>lorem</li> 
    <li class="last">lorem</li> 
</ul> 

我見李漂到在3行如何使用jQuery來選擇每行左邊(3華里的)找到該行中的最大高度,然後將該行中的其他行設置爲相同的高度?

這是我現在所擁有的,但它只看到李的整體,而不是單獨的行。

var maxHeight = 0; 

$('ul#list li').each(function() { 
    maxHeight = $(this).height() > maxHeight ? $(this).height() : maxHeight; 
}).height(maxHeight); 

回答

4

打破元素成排第一,那麼用戶的邏輯上獨立的每一行:

var items = $('ul#list li'); 
var total = items.length; 

for(i = 0; i < total; i+=3){ 
    var row = items.slice(i, Math.min(i + 2, total - 1)); 
    var maxHeight = 0; 
    row.each(function() { 
     maxHeight = $(this).height() > maxHeight ? $(this).height() : maxHeight; 
    }).height(maxHeight); 
} 
+0

工作就像一個魅力。謝謝。 – ATLChris 2012-04-27 11:12:27

-1

嘗試這樣的:

var getMaxHeight = function ($elms) { 
    var maxH = 0; 
    $elms.each(function() { 
     if ($(this).outerHeight() > maxH) { 
      maxH = $(this).outerHeight(); 
     } 
    }); 
    return maxH; 
}; 

var $li = $('#list li'); 
$li.height(getMaxHeight($li)); // Put this on load or doc.ready 
+0

我想運問的是如何調整每行中的項目相對於行中的其他項目而不是整個集合的大小。 – kroehre 2012-04-27 02:49:31

+0

是的,是我問的。我在問題中發佈的代碼與此完全相同。我正在尋找可以在每行基礎上工作的內容。 – ATLChris 2012-04-27 11:05:46

0

如果你可以在容器設置爲overflow: hidden,你可以做到這一點不使用JavaScript,通過使用一個非常大的padding-bottom和一個同樣大的負margin-bottom(和保存底部的視覺填充物,將margin-bottom移近0以補償)。例如:

#list { 
    overflow: hidden; 
} 
#list li { 
    padding-bottom: 1000px; 
    margin-bottom: -1000px; 
} 
-1

月這段代碼可以幫助你......

$("#list li:nth-child(3n)").each(function(){ 
    var maxHeight = Math.max.apply(Math, $(this).children().map(function(){ return $(this).outerHeight(); }).get()); 
    $(this).children().each(function(){ 
     $(this).height(maxHeight); 
    }); 
});