【问题标题】:Match element's height匹配元素的高度
【发布时间】:2015-05-21 13:35:03
【问题描述】:

我有几个彼此相邻的<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);
    });
})

有没有更好的方法来达到这个结果?

【问题讨论】:

  • 如果您不介意与旧版浏览器不兼容,您可以使用 CSS flexbox
  • 为什么不使用表格...在这些情况下它可能会有所帮助
  • 你解决了吗?我看到各种答案都通过了,但还没有接受。我的建议对您有帮助吗?

标签: javascript jquery html css dom


【解决方案1】:

就我个人而言,我这样做:

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

【讨论】:

  • 我们为什么不使用Math.max(a,b) 而不是比较?
  • 不,@pabgaran。如果当前列高度的值大于它,这将遍历每一列并更改变量max
【解决方案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)

【讨论】:

    【解决方案3】:

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

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

    JSFiddle Example

    【讨论】:

    • 我同意第一部分,但第二部分你可以像$(".services-area").css("height", max + "px");这样放在一行中
    • @Thalsan 嘿,不错的建议,我忽略了一次针对所有.services-area。我放弃了我的each,可以直接打电话给height
    【解决方案4】:
    var maxHeight = 0;
    $(".services-area").each(function () {
        maxHeight = Math.max(maxHeight, $(this).height());
    }).height(maxHeight);  
    

    DEMO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-14
      • 1970-01-01
      • 1970-01-01
      • 2011-10-16
      • 1970-01-01
      • 2011-05-10
      相关资源
      最近更新 更多