可能重复:
我有3个div。
如下所示:
<div class="features"></div>
<div class="features"></div>
<div class="features"></div>
它们将被文本填充。我不知道多少钱。问题是,它们的高度都是相等的,这是必须的。
如何使用jQuery (或CSS)找到最高的DIV,并将其他两个设置为相同的高度,创建3个相同高度的DIV。
这个是可能的吗?
发布于 2011-07-22 02:46:40
在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精心制作了a JSFiddle for this solution in a responsive grid。谢谢!
版本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);
});
版本3- sans jQuery
下面是一个不使用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";
});
发布于 2011-07-22 02:53:40
您可以使用jquery每个函数:
var highest;
var first = 1;
$('.features').each(function() {
if(first == 1)
{
highest = $(this);
first = 0;
}
else
{
if(highest.height() < $(this).height())
{
highest = $(this);
}
}
});
发布于 2011-07-22 02:51:40
您可以使用三列div,但必须像这样添加包装器
<div id="wrapper">
<div class="features"></div>
<div class="features"></div>
<div class="features"></div>
</div>
在head标签中放入以下内容
<style type="text/css">
#wrapper {
position:relative;
overflow:hidden;
}
.features {
position:absolute;
float:left;
width:200px; /* set to whatever you want */
height:100%;
}
</style>
无论其中一个框的宽度是多少,其他框的宽度也是一样的。希望这能有所帮助。如果没有,我很抱歉,我只是当场做了代码。
https://stackoverflow.com/questions/6781031
复制相似问题