javascript 如何动态更改 div 的高度以匹配包含它的 div 的大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8326273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I dynamically change the height of a div to match the size of the div containing it
提问by Bogdan
I got div1 and div2 with div2 containing div1 (and some other elements). I want to dynamically change the height of div1 to match the height of div2(- the height of the other elements) whenever div1 exceeds that height. The reason I don't just set div1's height outright is because div2's size isn't fixed and I want the horizontal scroll bar from div1 to stick to the bottom of its content and not to the bottom of div2.
我得到了 div1 和 div2,其中 div2 包含 div1(和一些其他元素)。我想在 div1 超过该高度时动态更改 div1 的高度以匹配 div2 的高度( - 其他元素的高度)。我不直接设置 div1 的高度的原因是因为 div2 的大小不是固定的,我希望 div1 的水平滚动条粘在其内容的底部而不是 div2 的底部。
I don't have any code to show since it's just two divs.
我没有任何代码可以显示,因为它只是两个 div。
If it helps, div1 will contain a table.
如果有帮助,div1 将包含一个表格。
Here's what I got so far:
这是我到目前为止所得到的:
if(document.getElementById("div1").offsetHeight > document.getElementById("div2").offsetHeight) {
document.getElementById("div1").style.height = document.getElementById("div1").parentNode.offsetHeight+"px";
document.getElementById("div1").style.overflowY = "scroll";
}
This works for setting the overflow but I can't get it to actually change the height of div1
这适用于设置溢出,但我无法实际更改 div1 的高度
Here's the working version:
这是工作版本:
document.getElementById("div1").style.height = '';
document.getElementById("div1").style.overflowY = "";
if(document.getElementById("div1").offsetHeight > document.getElementById("div2").offsetHeight) {
var height = document.getElementById("div2").offsetHeight - document.getElementById("other_data").offsetHeight;
document.getElementById("div1").style.height = parseInt(height)+"px";
document.getElementById("div1").style.overflowY = "scroll";
}
for those who might be having the same problem.
对于那些可能遇到同样问题的人。
采纳答案by tkone
Something like this would work. You can write an event listener to watch for page resize, of if you're dynamically changing the size of the "parent" div tag, you should just call the js code to resize the child div each time.
像这样的事情会起作用。您可以编写一个事件侦听器来监视页面调整大小,如果您正在动态更改“父”div 标签的大小,则每次都应该调用 js 代码来调整子 div 的大小。
HTML:
HTML:
<div id=div1><div id=div2></div></div>
JS:
JS:
div2 = document.getElementById('div2')
div2.style.height = div2.parentNode.offsetHeight+"px"