2012-03-05 104 views
0

我有這樣的jQuery的腳本,讓我的兩個div相同的高度:DIV同一高度

$(document).ready(function() {  
    var $sameHeightDivs = $('.sameh'); 
    var maxHeight = 0; 
    $sameHeightDivs.each(function() { 
     maxHeight = Math.max(maxHeight, $(this).outerHeight()); 
    }); 

    $sameHeightDivs.css({ height: maxHeight + 'px' }); 
}); 

我有兩個div:

<div class="sameh">div 1</div> 
<div class="sameh">div 2</div> 

的問題是,該div 1加載第一(我認爲這是問題),而實際上DIV2比DIV1高。但是腳本只是讓這兩個div的高度相同,這會使DIV2的高度與DIV1相同。

我該怎麼辦,讓DIV1跟隨DIV2的高度?

謝謝。

+0

順便說一句,你可以傳遞一個整數參數的'高度( )'設置高度的方法,而不是使用'.css(height:...)'。 – Blazemonger 2012-03-05 14:49:04

+0

我實際上看不到你的代碼有什麼問題 - 它應該盡我所能地工作。 – 2012-03-05 14:49:56

+0

http://jsfiddle.net/mblase75/9yFzE/ - 你的代碼在這裏工作得很好。 – Blazemonger 2012-03-05 14:50:28

回答

4

你可以從你的所有元素得到的最大高度,然後應用到其他:

// get the max height of a collection of elements using map 
var maxHeight = Math.max.apply(null, $(".sameh").map(function() 
{ 
    return $(this).outerHeight(); 
}).get()); 
// set all divs to the same height 
$('.sameh').css({ height: maxHeight + 'px' }); 

Working example hereDocs on .map() here