如何在 Javascript 中制作具有不均匀 div 内容的相同高度的行?



工作示例

注意:我有下面的JQuery代码对我有用,但我必须使用Javascript。 我有一个表格,其中有两列。 列的每一行必须具有相同的高度,但每行不包含完全相同的内容量。 容器类 "row" 在第一列中有 3 个div,在第二列中有 2 个div。

这是我的网页

<div class="table">
<div class="column">
<div class="row">
<div class="value-label">TEXT1</div>
<div class="compare-label">TEXT2</div>
<div class="comment-label">TEXT3</div>
</div>
</div>
<div class="column">
<div class="row">
<div class="value-label">TEXT1</div>
<div class="compare-label">TEXT2</div>
</div>
</div>
</div>

使用以下 JQuery 函数时,我的行高相同:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function($) { 
var heights = $(".row").map(function() {
return $(this).height();
}).get(),
maxHeight = Math.max.apply(null, heights);
$(".row").height(maxHeight);
});
</script>

我的问题是我的公司不允许使用JQuery,而且我在尝试在Javascript中完成同样的事情时遇到了很多问题。 我需要每列中行的高度相同,无论行内的div 数量如何,但在 Javascript 中。

更新:忘了补充一点,在某些情况下,3div 列将恢复为 2div 列。因此,高度需要根据显示的div 数量而改变。这只是一个包含一行的示例。我有 5 行跨两列执行此操作。

使用我喜欢使用的flexbox(CSS3)布局并推荐其他人使用它,只需使用以下CSS即可轻松实现上述目标:

.table {
display: flex; // to initialize flex
background: lightgrey;
justify-content: center; // horizontally centers its child contents
}
.table .column {
border: 1px solid black;
flex-basis: 40%; // used similar to width property
display: flex;
justify-content: center;
}

.table {
display: flex;
background: lightgrey;
justify-content: center;
}
.table .column {
border: 1px solid black;
flex-basis: 40%;
display: flex;
justify-content: center;
}
<div class="table">
<div class="column">
<div class="row">
<div class="value-label">TEXT1</div> 
<div class="compare-label">TEXT2</div> 
<div class="comment-label">TEXT3</div>
</div>
</div>
<div class="column">
<div class="row">
<div class="value-label">TEXT1</div>
<div class="compare-label">TEXT2</div>
</div>
</div>
</div>

如果您需要使用 JS 来执行此操作,我会做这样的事情

var rows = document.querySelectorAll(".row");
var heights = Array.prototype.slice
.apply(rows)
.map(function(row) {
return row.clientHeight;
}),
maxHeight = Math.max.apply(null, heights);
rows.forEach(function(row) {
row.style.height = maxHeight + "px";
});

建议您使用flexbox或像bootstrap这样的css网格系统

<div align="center">
<table id="tabular" cellpadding="0" cellspacing="0" border="2">
<tr class="thead">
<th width="10%" align="center" rowspan="2">something</th>
<th width="20%" align="center" colspan="3">something</th>
<th width="20%" align="center" colspan="3">something</th>
<th width="20%" align="center" colspan="3">something</th>
</tr>
<tr class="thead">
<th align="center">something</th>
<th align="center">something</th>
<th align="center">something</th>
<th align="center">something</th>
<th align="center">something</th>
<th align="center">something</th> 
<th align="center">something</th>
<th align="center">something</th>
<th align="center">something</th>
</tr>
</table>
</div>

最新更新