设置相对于“window.innerHeight”的高度无效

Setting height relative to `window.innerHeight` not working

本文关键字:高度 无效 innerHeight 相对于 window 设置      更新时间:2023-09-26

对于一些人来说,这可能是一个非常愚蠢的问题,但我肯定无法理解这背后的问题。代码相当简单,如下所示:

HTML:

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <title>####</title>
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="css.css">
    </head>
    <body onload="resizeDiv();">    
        <div id="testElement">ABCD</div>
        <div id="secElement">ABC</div>
        <script type="text/javascript" src="javascript.js"></script>
    </body>
</html>

CSS:

html , body{
    height:100%;
}
#testElement{
    background-color:black;
    color:white;
}
#secElement{
    font-size:50px;
}

JS:

(function immediate(){
    document.getElementById('secElement').textContent = window.innerHeight;
}());
function resizeDiv(){
    document.getElementById('testElement').style.height = (window.innerHeight - 50) * 0.9;
}

现在,通过此代码,具有id"testElement"的div的高度应该是window.innerHeight - 20的90%。但是,似乎什么都不起作用。请帮忙。

添加"px":

document.getElementById('testElement').style.height =  (window.innerHeight - 50) * 0.9 + "px";

body标记有一个分配给resizeDiv()onload处理程序,但您的脚本位于页面底部,因此onload处理程序无法引用它。

使用document.getElementById('testElement').setAttribute("style","height:" + (window.innerHeight - 50) * 0.9) + ' px';您可以在此处找到使用它的更多解释:在JavaScript 中设置div宽度和高度