使用jQuery / CSS查找所有元素中最高的元素

时间:2011-07-21 18:42:50

标签: jquery css

  

可能重复:
  CSS - Equal Height Columns?

我有3个div。

像这样:

<div class="features"></div>
<div class="features"></div>
<div class="features"></div>

他们将充满文字。我不知道多少钱。问题是,它们都是平等的高度。

我如何使用jQuery(或CSS)找到最高的DIV并将其他两个设置为相同的高度,创建3个相等高度的DIV。

这可能吗?

3 个答案:

答案 0 :(得分:183)

你不能轻易地选择高度或在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";
});

and here it is in ES6

答案 1 :(得分:3)

你可以使用jquery各个函数:

var highest;
var first = 1;
$('.features').each(function() {
   if(first == 1)
   {
        highest = $(this);
        first = 0;
   }
   else
   {
        if(highest.height() < $(this).height())
        {
              highest = $(this);
        }
   }
  });

答案 2 :(得分:0)

你可以做三个列div,但你必须像这样添加包装器

<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>

无论宽度是多少,其他的都是相同的。希望这可以帮助。我很抱歉,如果没有,我只是当场制作代码。