javascript - 使每两个元素具有相同的高度

标签 javascript jquery

我有一个装有许多 child 的容器,这些 child 的高度必须相同,但只能成对出现。 例如,第一个和第二个元素需要与两个元素中最高的一样高,第三个和第四个元素需要与第一个和第二个 child 的高度无关。

我当前的代码,等于所有 child 的高度

$(document).ready(function(){
        // Select and loop the container element of the elements you want to equalise
        $('.parent').each(function(){

            // Cache the highest
            var highestBox = 0;

            // Select and loop the elements you want to equalise
            $('.child', this).each(function(){

                // If this box is higher than the cached highest then store it
                if($(this).height() > highestBox) {
                    highestBox = $(this).height();
                }

            });

            // Set the height of all those children to whichever was highest
            $('.child',this).height(highestBox);

        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent'>
  <div class='child'>some dynamic content</div>
  <div class='child'>some dynamic content</div>
  <div class='child'>some dynamic content</div>
  <div class='child'>some dynamic content</div>
  <div class='child'>some dynamic content</div>
  <div class='child'>some dynamic content</div>
</div>

最佳答案

您可能想要实现类似网格的行为,无需 JavaScript 使用 flexbox 即可轻松实现:

  /* Purely for visual appearance */
.parent {
  width: 300px;  
}
.child {
  background: linear-gradient(45deg, lightgreen, yellow);
  padding: 5px;
  box-sizing: border-box;
}
/* Actual logic */
.parent {
  display: flex;
  flex-wrap: wrap;
  align-items: stretch;
}
.child {
  flex: 1 1 50%;
}
<div class='parent'>
  <div class='child'>a bit of text</div>
  <div class='child'>very large amount of content to make height largest across all rows</div>
  <div class='child'>a b c d e f g h i j k l m n o p q r s t u v w x y z</div>
  <div class='child'>a b c</div>
</div>

关于javascript - 使每两个元素具有相同的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47431634/

相关文章:

javascript - 如何在单个网页中使用 introJs 设置两个介绍之旅?

javascript - 更新函数 JQuery 内的变量

javascript - 为什么我不能通过单击 DIV 来加粗文本?

javascript - 如何区分生成的元素和选定的元素?

javascript - JavaScript 更改输入值时的事件?

javascript - 谷歌地图引用标记监听器

javascript - 通过 JS 或 PHP 从新的 youtube 2015 下载视频

jquery - 在 mouseenter 和 mouseleave 上与 HTML 交互

javascript - JQuery 中减法后负结果的任何解决方案

javascript - 如何检查值是否未定义以便不将其添加为对象字段?