可能是重复问题:
CSS - 如何让列等高?
我有3个div。
像这样:
<div class="features"></div>
<div class="features"></div>
<div class="features"></div>
这些DIV将会被填充文本内容,我不确定有多少文本。问题是,它们必须保持相等的高度。
我应该如何使用jQuery(或CSS)找到最高的DIV并设置另外两个DIV的高度与之相同,从而创建3个等高的DIV?
这种操作是否可行?
可能是重复问题:
CSS - 如何让列等高?
我有3个div。
像这样:
<div class="features"></div>
<div class="features"></div>
<div class="features"></div>
这些DIV将会被填充文本内容,我不确定有多少文本。问题是,它们必须保持相等的高度。
我应该如何使用jQuery(或CSS)找到最高的DIV并设置另外两个DIV的高度与之相同,从而创建3个等高的DIV?
这种操作是否可行?
在CSS中无法轻松选择或比较元素的高度,但是使用jQuery和一些迭代可以轻松地解决这个问题。我们将循环遍历每个元素并跟踪最高的元素,然后再次循环并将每个元素的高度设置为最高元素的高度(运行JSFiddle):
$(document).ready(function() {
var maxHeight = -1;
$('.features').each(function() {
maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
});
$('.features').each(function() {
$(this).height(maxHeight);
});
});
[补充说明]
Sheriffderek制作了一个响应式网格的JSFiddle解决方案。谢谢!
[版本2]
这里是一个更干净的版本,使用函数式编程:
$(document).ready(function() {
// Get an array of all element heights
var elementHeights = $('.features').map(function() {
return $(this).height();
}).get();
// Math.max takes a variable number of arguments
// `apply` is equivalent to passing each height as an argument
var maxHeight = Math.max.apply(null, elementHeights);
// Set each height to the max height
$('.features').height(maxHeight);
});
[无jQuery版本-第3版]
这是一个更新后的版本,不使用jQuery(在JSFiddle上工作):
var elements = document.getElementsByClassName('features');
var elementHeights = Array.prototype.map.call(elements, function(el) {
return el.clientHeight;
});
var maxHeight = Math.max.apply(null, elementHeights);
Array.prototype.forEach.call(elements, function(el) {
el.style.height = maxHeight + "px";
});
(这里是ES6版本)
$('.features').height(maxHeight);
。 - Tom$(window)resize();
- 只有第一次有效,而 -1
仍然是个谜。让我们看看我这一年学到了什么,能否稍微调整一下。 - sheriffderekvar highest;
var first = 1;
$('.features').each(function() {
if(first == 1)
{
highest = $(this);
first = 0;
}
else
{
if(highest.height() < $(this).height())
{
highest = $(this);
}
}
});
<div id="wrapper">
<div class="features"></div>
<div class="features"></div>
<div class="features"></div>
</div>
<style type="text/css">
#wrapper {
position:relative;
overflow:hidden;
}
.features {
position:absolute;
float:left;
width:200px; /* set to whatever you want */
height:100%;
}
</style>
无论其中一个框的宽度是多少,其他框也会得到相同的宽度。希望这可以帮到你。如果不能,我很抱歉,因为我只是现场编写代码。