繁体   English   中英

匹配元素的高度

[英]Match element's height

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

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

就个人而言,我这样做:

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

您可以使用CSS弹性框

.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

这是另一种可以解决这个问题的方法,利用JavaScript max()方法

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

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

JSFiddle示例

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

DEMO

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM