首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用jQuery/CSS查找所有元素中最高的元素

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

Stack Overflow用户
提问于 2011-07-22 02:42:50
回答 3查看 69.6K关注 0票数 64

可能重复:

CSS - Equal Height Columns?

我有3个div。

如下所示:

代码语言:javascript
复制
<div class="features"></div>
<div class="features"></div>
<div class="features"></div>

它们将被文本填充。我不知道多少钱。问题是,它们的高度都是相等的,这是必须的。

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

这个是可能的吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-07-22 02:46:40

在CSS中你不能很容易地通过高度或比较来选择,但是jQuery和一些迭代应该可以很容易地解决这个问题。我们将遍历每个元素并跟踪最高的元素,然后再次循环并将每个元素的高度设置为最高元素的高度(工作JSFiddle):

代码语言:javascript
复制
 $(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

下面是一个使用函数式编程的更简洁的版本:

代码语言:javascript
复制
$(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)的更新版本:

代码语言:javascript
复制
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)

票数 195
EN

Stack Overflow用户

发布于 2011-07-22 02:53:40

您可以使用jquery每个函数:

代码语言:javascript
复制
var highest;
var first = 1;
$('.features').each(function() {
   if(first == 1)
   {
        highest = $(this);
        first = 0;
   }
   else
   {
        if(highest.height() < $(this).height())
        {
              highest = $(this);
        }
   }
  });
票数 3
EN

Stack Overflow用户

发布于 2011-07-22 02:51:40

您可以使用三列div,但必须像这样添加包装器

代码语言:javascript
复制
<div id="wrapper">
 <div class="features"></div>
 <div class="features"></div>
 <div class="features"></div>
</div>

在head标签中放入以下内容

代码语言:javascript
复制
<style type="text/css">
#wrapper {
  position:relative;
  overflow:hidden;
}

.features {
  position:absolute;
  float:left;
  width:200px; /* set to whatever you want */
  height:100%;
}
</style>

无论其中一个框的宽度是多少,其他框的宽度也是一样的。希望这能有所帮助。如果没有,我很抱歉,我只是当场做了代码。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6781031

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档