开发者

Dynamic height adjustment

开发者 https://www.devze.com 2023-03-21 08:03 出处:网络
I have two boxes like: <div class=\"box\"> <div class=\"content\">Here goes content 1.</div>

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. The div stretches. How can I achieve that the class changes the height so that the second content will have the same height as content 1?


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):

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


Put them inside a parent DIV and make the height auto for the second one.

0

精彩评论

暂无评论...
验证码 换一张
取 消