javascript - 将少数元素的最高高度设置为Javascript中的所有元素
问题描述
我必须得到几个元素的高度(例如:.content-one > .title)并为所有项目设置最高的数字。
<div class="content-one">
<h3 class="title">Section One</h3>
</div>
<div class="content-two">
<h3 class="title">Section Two</h3>
</div>
这是我写的代码。
maxHeight('.content-one');
maxHeight('.content-two');
function maxHeight(element) {
const contents = document.querySelectorAll(element);
contents.forEach(function(content) {
var title = content.getElementsByClassName('title')[0];
if (title.clientHeight > 20) {
title.style.height = 40 + "px";
console.log("done");
}
});
}
在这里,它检查高度并尝试设置高度。但它只为高度> 20的元素设置高度。什么是最好的解决方案?
解决方案
@Suresh.W,尝试使用给定的解决方案,在第一个循环中,您必须获取最高高度,然后您可以将其分配给您的控件
$(document).ready(function(){
maxHeight('.content-one');
maxHeight('.content-two');
function maxHeight(element) {
const contents = document.querySelectorAll(element);
var allHeight = [];
var setheight= 40;
contents.forEach(function(content) {
var title = content.getElementsByClassName('title')[0];
allHeight.push(title.clientHeight);
if(Math.max(allHeight) > 20)
setheight = 40;
else
setheight = Math.max(allHeight);
});
var elems = document.querySelectorAll(".title");
var index = 0, length = elems.length;
for ( ; index < length; index++) {
elems[index].style.height =setheight + "px";
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content-one">
<h4 class="title">Section One</h4>
</div>
<div class="content-two">
<h3 class="title">Section Two</h3>
</div>
推荐阅读
- swift - 如何在以编程方式编写的视图上正确显示 CAGradientLayer?
- .net-core - 单元测试是否将 Cors 添加到 ServiceCollection
- where-clause - 在 QlikSense 脚本中保留满足条件的行
- node.js - 当我尝试使用来自正文(PATCH)的请求访问数据时,“超出最大调用堆栈大小”
- excel - 我想比较 3 个不同的列(B、C、D)值然后想在 F 列中获得更高的值结果
- android - 如何在圆形视图android中查看视频
- java - 如何在 Hibernate 中覆盖 Session.save()?
- r - R 中的 p.adjust 函数为所有原始 p 值提供了意外的值 1
- python - 具有一个热编码数据的 LSTM 的输入形状
- javascript - 循环遍历具有类名的项目并隐藏它们