Javascript 根据父div内部剩余的空间设置div的初始高度
我有3个div: .main\u content、.content\u top、.content\u bottom .main_content设置为100%,但100%不是浏览器窗口的大小,它位于我的页面中间 .content_top设置为60%的高度 我想通过javascript将.content\u bottom的高度设置为.main\u内容中剩余的可用空间。 例如,如果.main_内容高达800px,而.content_top高达600px,我想将.content_bottom设置为200pxJavascript 根据父div内部剩余的空间设置div的初始高度,javascript,Javascript,我有3个div: .main\u content、.content\u top、.content\u bottom .main_content设置为100%,但100%不是浏览器窗口的大小,它位于我的页面中间 .content_top设置为60%的高度 我想通过javascript将.content\u bottom的高度设置为.main\u内容中剩余的可用空间。 例如,如果.main_内容高达800px,而.content_top高达600px,我想将.content_bottom设置为200
这是一个简单的例子,我的情况并不像指定40%或让浏览器来决定那样简单。首先,目前在.content\u顶部有46像素的填充。我正在做一个.content\u top和.content\u bottom之间的分割屏幕界面,拖动一个条来调整两者的大小。这主要是工作,只是有麻烦的底部部分。能够将.content_bottom设置为特定高度(即198px)将解决我当前的所有问题。很高兴详细介绍这个例子,并深入研究一些实际的代码,但希望有一个简单的方法来计算这个,并且很难找到一个跨浏览器工作的好例子,谢谢 简单jQuery解决方案:
$("content_bottom").css({"height": $("main_content").height() + $("content_top").height());
假设您使用的是香草JavaScript(而不是库),我建议:
var cBs = document.getElementsByClassName('content_bottom');
for (var i=0,len=cBs.length; i<len; i++){
var p = cBs[i].parentNode;
cBs[i].style.height = (parseInt(p.offsetHeight,10) - parseInt(p.getElementsByClassName('content_top')[0].offsetHeight,10)) + 'px';
}
var cBs=document.getElementsByClassName('content_bottom');
对于(var i=0,len=cBs.length;ielement.style.height
只适用于内联样式…最好使用element.offsetHeight
。非常好,您甚至在parseInt
+1中得到了基数参数,好先生,请拍拍一下:)(for
-loop中的var
是坏的)