【问题标题】:Dynamic height adjustment动态高度调节
【发布时间】:2011-07-20 15:55:55
【问题描述】:

我有两个盒子,比如:

<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;}

现在可能是内容 1 的文本不适合 150 像素的高度。 div 伸展。 如何实现类更改高度以使第二个内容与内容 1 具有相同的高度?

【问题讨论】:

  • 你可以使用JQuery还是必须依赖纯javascript?
  • 很遗憾我不能使用 jQuery...

标签: javascript html css height


【解决方案1】:

这感觉不太优雅,但它可以工作(至少在 FF、Chrome 和 Safari for Mac 中,因为我没有时间在 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;}

不要忘记从你的css中删除height:150px,否则元素的高度将不会被调整。

【讨论】:

  • 您好,感谢您的帖子。我会看看我能用它做什么。 ;-)
【解决方案2】:

将它们放在父 DIV 中,并为第二个设置自动高度。

【讨论】:

  • 嗨,这是个好主意,但不幸的是,由于结构本身,我无法更改任何 html 结构。
猜你喜欢
  • 2020-12-17
  • 1970-01-01
  • 2018-02-13
  • 1970-01-01
  • 1970-01-01
  • 2018-03-23
  • 2016-04-25
  • 2012-02-10
  • 2011-11-25
相关资源
最近更新 更多