我有一个装有许多 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/