我有两个盒子:
<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;}
现在可能是content 1的文字不适合150px的高度。 div 拉伸(stretch)。 我怎样才能实现类更改高度,以便第二个内容与内容 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
否则元素的高度将不会调整。
关于javascript - 动态高度调整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6758253/