简体   繁体   English

匹配元素的高度

[英]Match element's height

I've got a few <div> elements next to each other and I'd like to match their height to the highest one. 我有几个<div>元素彼此相邻,我想将它们的高度与最高的一个相匹配。 Currently I do it like this: 目前我这样做:

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);
    });
})

Are there better ways to achieve this result? 是否有更好的方法来实现这一结果?

Personally, I do this: 就个人而言,我这样做:

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

Then I can just call it when ever I want 然后我可以随时调用它

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

See Live example here http://jsfiddle.net/Panomosh/t6xsjef7/ 在这里查看实例.http://jsfiddle.net/Panomosh/t6xsjef7/

You could use CSS flex box : 您可以使用CSS弹性框

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

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

Works in all modern browsers, with partial support for IE10, but fails before that ( http://caniuse.com/#search=flex ) 适用于所有现代浏览器,部分支持IE10,但在此之前失败( http://caniuse.com/#search=flex

Here is another way you can approach this, leveraging the JavaScript max() Method 这是另一种可以解决这个问题的方法,利用JavaScript max()方法

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

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

JSFiddle Example JSFiddle示例

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

DEMO DEMO

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

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