如何动态更改div的高度以匹配包含它的div的大小 [英] How can I dynamically change the height of a div to match the size of the div containing it

查看:38
本文介绍了如何动态更改div的高度以匹配包含它的div的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了div1和div2,其中div2包含div1(和其他一些元素).每当div1超过该高度时,我都希望动态更改div1的高度以匹配div2的高度(-其他元素的高度).我之所以不直接设置div1的高度,是因为div2的大小不是固定的,我希望div1的水平滚动条停留在其内容的底部而不是div2的底部.

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.

由于只有两个div,所以没有任何代码可显示.

I don't have any code to show since it's just two divs.

如果有帮助,div1将包含一个表.

If it helps, div1 will contain a table.

这是我到目前为止所得到的:

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

这可用于设置溢出,但我无法真正改变div1的高度

This works for setting the overflow but I can't get it to actually change the height of div1

这是工作版本:

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.

推荐答案

类似的方法将起作用.您可以编写一个事件侦听器来监视页面的大小,如果您正在动态更改父" div标签的大小,则每次只需调用js代码来调整子div的大小即可.

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.

HTML:

<div id=div1><div id=div2></div></div>

JS:

div2 = document.getElementById('div2')
div2.style.height = div2.parentNode.offsetHeight+"px"

这篇关于如何动态更改div的高度以匹配包含它的div的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆