2011-06-28 50 views
1

我有這樣的代碼:jQuery的格高度計算分別

var maxHeight = 0; 
$('div.height').each(function() { maxHeight = Math.max(maxHeight, $(this).height());  }).height(maxHeight); 

此代碼計算每個框,即使在長度。但我希望每個盒子分別計算長度。我怎樣才能做到這一點?

我的HTML

<div class="height"> 
    <div class="overlay height"></div> 
    Content 
</div> 

<div class="height"> 
    <div class="overlay height"></div> 
    Content 
</div> 

回答

1

我必須找出自己這是解決方案:

$('div.height').each(function() { 
    hParent = $(this).height(); 
    hChild = $(this).find('div.overlay').height(); 
    maxHeight = Math.max(hParent, hChild);  
    $(this).height(maxHeight); 
    $(this).find('div.overlay').css("height",(maxHeight-72)+"px"); 
}); 
+0

如果您對該解決方案感到滿意,則應將答案標記爲「已接受」(答案左側的勾號)。 – Spycho

1
$('div.height').each(function() { 
    maxHeight = Math.max(maxHeight, $(this).height());  
    $(this).height(maxHeight); 
}) 
+0

在這種情況下,如果$(「div.height」)返回的div了在高度巧合的增加則什麼都不會改變的數組作爲maxHeight的頁面將始終是當前DOM元素的高度。不確定這是他所要求的,但是如果是這樣的話,在初始循環完成後將迭代所有div.height元素並將高度設置爲maxHeight。 – MoarCodePlz

+0

@MoarCodePlz - true。但這是OP所做的...... – Neal

+0

嗨尼爾,這不工作,現在沒有計算了...... – Maanstraat

0

在你當前的代碼要設置一切maxHeight的現在值,而不是maxHeight的最終值。如果我的理解是你打算做正確,然後嘗試分離出來這樣:

var maxHeight = 0; 

$('div.height').each(function() { maxHeight = Math.max(maxHeight, $(this).height()); }); 

$('div.height').height(maxHeight); 

這將最終maxHeight適用於所有的div。

+0

這是OP已經在做什麼....你只是讓它更長.... – Neal

+0

是的,你說得對。我認爲.height是在.each函數中。 – MoarCodePlz