匹配元素的高度

时间:2015-05-21 13:35:03

标签: javascript jquery html css dom

我有几个<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);
    });
})

是否有更好的方法来实现这一结果?

4 个答案:

答案 0 :(得分:4)

就个人而言,我这样做:

$.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/

答案 1 :(得分:2)

您可以使用CSS flex box

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

快速笔:http://codepen.io/alexcoady/pen/KpgqGB

适用于所有现代浏览器,部分支持IE10,但在此之前失败(http://caniuse.com/#search=flex

答案 2 :(得分:1)

这是另一种方法,可以利用JavaScript max() Method

来解决这个问题
var max = Math.max.apply(Math, $('.services-area').map(function() {
    return $(this).height();
}));

$('.services-area').height(max)

JSFiddle Example

答案 3 :(得分:0)

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

<强> DEMO

相关问题