首页 > 解决方案 > 将少数元素的最高高度设置为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的元素设置高度。什么是最好的解决方案?

标签: javascriptforeachheight

解决方案


@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>


推荐阅读