通过窗口大小调整动态更改div高度

时间:2013-07-18 04:49:39

标签: javascript window-resize

我希望在调整窗口大小时更改div的高度。我知道可以使用height:100%;使用css完成,但这对我需要的东西不起作用。我希望在没有JQuery或任何其他框架的纯JavaScript中实现这一点。

这就是我所做的:

<div id="left">
<div id="inner">

</div>
</div>

CSS

#left{

margin-top:40px;
width:200px;
height:576px;
background:white;

}
#inner{

height:100%;
overflow-y:scroll;
}

JAVASCRIPT

window.onload=
window.onresize=function(){
var left=document.getElementById('left');
var window_height = window.innerheight;
if ( window_height > 600px ) { left.style.height = document.body.offsetHeight
+"px";    } 
else { } 
} 

id为left的div必须具有相同的余量。我只是想改变div的高度以匹配内部窗口高度(以px no%为单位)。

谢谢。

2 个答案:

答案 0 :(得分:1)

window.innerheight应为window.innerHeight(大写H)。请注意,IE在IE9之前不支持它。

另请注意,您在此处将元素与数字进行比较:

if ( left < window_height )
//   ^--- element

您可能希望从left获得高度,因为这种情况永远不会成真。

答案 1 :(得分:1)

请参阅jsfiddle jsfiddle

尝试使用console.log来了解您处理的值或对象

window.onload = window.onresize = function () {
    var left = document.getElementById('left');
    var window_height = window.innerHeight;
    console.log(left.offsetHeight);
    console.log(window_height);
    if (left.offsetHeight < window_height) {
        left.style.height = window_height + "px";

    } else {}
}

首先设置100%知道确切的高度数,然后再分配回高度。

更新了代码updated jsfiddle

window.onload = window.onresize = function () {
    var left = document.getElementById('left');

    console.log(left.offsetHeight);
    var window_height = window.innerHeight;

    if (left.offsetHeight < window_height) {
        left.style.height = '100%';    
        left_height=left.offsetHeight;
        console.log(left_height);
        left.style.height = left_height + "px";

    } else {}
};
相关问题