简体   繁体   English

获取div的高度,并根据检测到的高度调整其他高度

[英]Get height of the div and adjust others based on height detected

Need help to get height of the li div element adjust the height of other li div based on the highest height detected. 需要帮助以获取li div元素的高度,然后根据检测到的最高高度来调整其他li div的高度。

It works fine on onload. 在加载时工作正常。 When i refresh the page, script not working again. 当我刷新页面时,脚本不再起作用。 Please guide me. 请指导我。

JS: JS:

var maxHeight = -1;

$('.product-item .content').each(function() {
  maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
});

$('.product-item .content').each(function() {
  $(this).height(maxHeight);
});

HTML: HTML:

<ul id="related-products">

    <li>
        <div class="product-item">
            <div class="image">
                <img src="/image1.png" alt="">
            </div>
            <div class="content">Hello</div>
        </div>
    </li>

    <li>
        <div class="product-item">
            <div class="image">
                <img src="/image2.png" alt="">
            </div>
            <div class="content">Hello1<br>Hello2<br>Hello</div>
        </div>
    </li>

</ul>

So I have re written you HTML code, because you have useless div : 因此,我为您编写了HTML代码,因为您的div没有用:

<ul id="related-products">
  <li class="product-item min-height407">
    <div class="image">
      <img src="/content/protect-badge.png" alt="">
      </div>
    <div class="content">Hello</div>
  </li>
  <li class="product-item min-height407">
    <div class="image">
      <img src="/content/protect-badge.png" alt="">
    </div>
    <div class="content">Hello1<br>Hello2<br>Hello</div>
  </li>
</ul>

Then in JS, you set a variable maxHeight to 0 , and loop on ul li , to find the utmost value of li. 然后在JS中,将变量maxHeight设置为0 ,并在ul li上循环查找li的最大值。 Then, you happen to all of your li the value. 然后,你碰巧所有的li值。 You may apply it at the document ready. 您可以在准备好文档时应用它。

var maxHeight = 0;
$('#related-products li').each(function (i,e) {
    if ($(e).height() > maxHeight) {
        maxHeight = $(e).height();
    }
});
// And then apply this max height to all li into ul#related-products
$('#related-products li').css({'height' : maxHeight});

Please find this jsfiddle . 请找到这个jsfiddle I have add style for your comprehension 我为您的理解增添了风格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM