我有几个<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 :(得分:4)
就个人而言,我这样做:
$.fn.sameHeight = function(){
var max = 0;
this.each(function(){
max = Math.max($(this).height(),max);
});
return this.height(max);
};
然后我可以随时调用它
$('.column').sameHeight();
答案 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)
答案 3 :(得分:0)
var maxHeight = 0;
$(".services-area").each(function () {
maxHeight = Math.max(maxHeight, $(this).height());
}).height(maxHeight);
<强> DEMO 强>