2015-05-21 134 views
2

我已經有幾個<div>元素彼此相鄰,我想匹配它們的高度到最高的一個。目前我這樣做:匹配元素的高度

jQuery(function($) { 
    var maxHeight = 0; 
    $(".services-area").each (function (index) { 
     if (maxHeight < $(this).height()) { 
      maxHeight = $(this).height(); 
     } 
    }); 

    $(".services-area").each (function (index) { 
     $(this).height(maxHeight); 
    }); 
}) 

有沒有更好的方法來實現這個結果?

+0

您可以使用CSS [Flexbox的(http://stackoverflow.com/questions/27090585/equal-height-flexbox-columns-in-chrome),如果你不介意與舊的瀏覽器不兼容。 – Blazemonger

+1

爲什麼不使用表...在這些情況下,它可能會有所幫助 – pabgaran

+0

您是否解決了這個問題?我看到各種答案已經通過但尚未接受。我的建議能夠幫助你嗎? – scniro

回答

3

就個人而言,我這樣做:

$.fn.sameHeight = function(){ 
    var max = 0; 
    this.each(function(){ 
     max = Math.max($(this).height(),max); 
    }); 
    return this.height(max); 
}; 

然後我就可以把它當過我想

$('.column').sameHeight(); 

看到這裏 http://jsfiddle.net/Panomosh/t6xsjef7/

+0

但是,這隻適用於如果第一個div是最高... – pabgaran

+2

爲什麼我們不使用'Math.max(a,b)'而不是比較? – Blazemonger

+0

不,@pabgaran。如果當前列高度的值大於此值,則這將迭代每列,並更改變量「max」。 –

2

活生生的例子,您可以使用CSS flex box

.container { 
    display: flex; 
    align-items: stretch; // Matches height of items 
    justify-content: space-between; // Arranges horizontally 
} 

快速筆:在這之前(http://caniuse.com/#search=flex

1

這裏是另外一種方式來處理這個,借力JavaScript max() Method

var max = Math.max.apply(Math, $('.services-area').map(function() { 
    return $(this).height(); 
})); 

$('.services-area').height(max) 
http://codepen.io/alexcoady/pen/KpgqGB

適用於所有現代瀏覽器,與IE10部分支持,但失敗

JSFiddle Example

+0

我同意第一部分,但第二部分可以像'''$(「。services-area」)。css(「height」,max +「px」);''' – Thalsan

+1

@Thalsan嘿好建議,我忽略了一次針對所有'.services-area'。我放棄了我的'each',可以直接調用'height' – scniro

0
var maxHeight = 0; 
$(".services-area").each(function() { 
    maxHeight = Math.max(maxHeight, $(this).height()); 
}).height(maxHeight); 

DEMO