小编典典

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

css

我有3个div。

像这样:

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

他们将充满文字。我不确定多少。问题是,所有高度都必须相等。

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

这可能吗?


阅读 396

收藏
2020-05-16

共1个答案

小编典典

您不能轻松地通过高度选择或在CSS中进行比较,但是jQuery和一些迭代应该可以轻松解决此问题。我们将遍历每个元素并跟踪最高的元素,然后再次遍历并将每个元素的高度设置为最高:

 $(document).ready(function() {
   var maxHeight = -1;

   $('.features').each(function() {
     maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
   });

   $('.features').each(function() {
     $(this).height(maxHeight);
   });
 });

[附录]

[版本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]
):

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";
});
2020-05-16