简体   繁体   English

动态高度调节

[英]Dynamic height adjustment

I have two boxes like:我有两个盒子,比如:

<div class="box">
    <div class="content">Here goes content 1.</div>
</div>
<div class="box">
    <div class="content">Here goes content 2.</div>
</div>


.content {height:150px;width:65px;}

Now it can be that the text of content 1 doesn't fit the height of 150px.现在可能是内容 1 的文本不适合 150px 的高度。 The div stretches. div 伸展。 How can I achieve that the class changes the height so that the second content will have the same height as content 1?如何实现 class 更改高度,以便第二个内容与内容 1 具有相同的高度?

Put them inside a parent DIV and make the height auto for the second one.将它们放在父 DIV 中,并为第二个设置自动高度。

This does not feel too elegant, but it works (at least in FF, Chrome and Safari for Mac, as I did not have the time to test it in IE):这感觉不太优雅,但它可以工作(至少在 Mac 的 FF、Chrome 和 Safari 中,因为我没有时间在 IE 中测试它):

<script type="text/javascript">
   window.onload = function() {
       var minHeight = 150;
       var contentDivs = [];
       var divs = document.getElementsByTagName("div");

       // find the content div with the tallest height
       for (var i=0; i < divs.length; i++) {
          var div = divs[i];
          if (div.className == "content") {
             minHeight = Math.max(minHeight, div.offsetHeight);
             contentDivs.push(div);
          }
       }

       // set the content divs' height to the tallest height
       for (var j=0; j < contentDivs.length; j++) {
          var contentDiv = contentDivs[j];
          contentDiv.style.height = minHeight + "px";
       }
   }
</script>

.content {width:65px;}

Don't forget to remove the height:150px from your css or the height of the elements won't be adjusted.不要忘记从 css 中删除height:150px ,否则不会调整元素的高度。

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

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