动态设置DIV的高度
时间:2020-03-05 18:44:35 来源:igfitidea点击:
在Web应用程序中,我的页面包含一个DIV,该DIV的自动宽度取决于浏览器窗口的宽度。
我需要为该对象设置自动高度。 DIV从顶部屏幕开始大约300px,它的高度应使其延伸到浏览器屏幕的底部。我有一个容器DIV的最大高度,所以div的最小高度必须是最小。我相信我可以将其限制在CSS中,并使用Javascript处理DIV的大小调整。
我的JavaScript不够理想。我可以编写一个简单的脚本来为我做到这一点吗?
编辑:
DIV包含一个控件,该控件执行自己的溢出处理(实现自己的滚动条)。
解决方案
回答
如果发生溢出该怎么办?如果要使其仅到达窗口底部,请使用绝对定位:
div { position: absolute; top: 300px; bottom: 0px; left: 30px; right: 30px; }
这样会将DIV从两侧各放30px,从屏幕顶部放300px,并与底部齐平。添加overflow:auto;
以处理内容大于div的情况。
编辑:@谁将其标记为下来,一个解释将是很好的...答案有问题吗?
回答
DIV包含一个控件,该控件执行自己的溢出处理。
回答
如果我了解要求,就可以解决这个问题:
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use // window.innerWidth and window.innerHeight var windowHeight; if (typeof window.innerWidth != 'undefined') { windowHeight = window.innerHeight; } // IE6 in standards compliant mode (i.e. with a valid doctype as the first // line in the document) else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) { windowHeight = document.documentElement.clientHeight; } // older versions of IE else { windowHeight = document.getElementsByTagName('body')[0].clientHeight; } document.getElementById("yourDiv").height = windowHeight - 300 + "px";
回答
document.getElementById('myDiv')。style.height = 500;
这是动态调整对象高度所需的非常基本的JS代码。我只是在有一些auto height属性的地方做了这个事情,但是当我通过XMLHttpRequest添加一些内容时,我需要调整父div的大小,而offsetheight属性在IE6 / 7和FF3中起到了作用
回答
尝试以下简单的特定功能:
function resizeElementHeight(element) { var height = 0; var body = window.document.body; if (window.innerHeight) { height = window.innerHeight; } else if (body.parentElement.clientHeight) { height = body.parentElement.clientHeight; } else if (body && body.clientHeight) { height = body.clientHeight; } element.style.height = ((height - element.offsetTop) + "px"); }
它不取决于当前距指定的主体顶部的距离(以防300px变化)。
编辑:顺便说一句,我们希望每次用户更改浏览器大小时在该div上调用此函数,因此,我们当然需要为此连接事件处理程序。
回答
进行较小的更正:
function rearrange() { var windowHeight; if (typeof window.innerWidth != 'undefined') { windowHeight = window.innerHeight; } // IE6 in standards compliant mode (i.e. with a valid doctype as the first // line in the document) else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) { windowHeight = document.documentElement.clientHeight; } // older versions of IE else { windowHeight = document.getElementsByTagName('body')[0].clientHeight; } document.getElementById("foobar").style.height = (windowHeight - document.getElementById("foobar").offsetTop - 6)+ "px"; }