2012-03-05 102 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