匹配元素的高度
我已经有几个<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();
但是,这只适用于如果第一个div是最高... – pabgaran
为什么我们不使用'Math.max(a,b)'而不是比较? – Blazemonger
不,@pabgaran。如果当前列高度的值大于此值,则这将迭代每列,并更改变量“max”。 –
活生生的例子,您可以使用CSS flex box:
.container {
display: flex;
align-items: stretch; // Matches height of items
justify-content: space-between; // Arranges horizontally
}
快速笔:在这之前(http://caniuse.com/#search=flex)
这里是另外一种方式来处理这个,借力JavaScript max()
Method
var max = Math.max.apply(Math, $('.services-area').map(function() {
return $(this).height();
}));
$('.services-area').height(max)
http://codepen.io/alexcoady/pen/KpgqGB
适用于所有现代浏览器,与IE10部分支持,但失败
var maxHeight = 0;
$(".services-area").each(function() {
maxHeight = Math.max(maxHeight, $(this).height());
}).height(maxHeight);
您可以使用CSS [Flexbox的(http://stackoverflow.com/questions/27090585/equal-height-flexbox-columns-in-chrome),如果你不介意与旧的浏览器不兼容。 – Blazemonger
为什么不使用表...在这些情况下,它可能会有所帮助 – pabgaran
您是否解决了这个问题?我看到各种答案已经通过但尚未接受。我的建议能够帮助你吗? – scniro