Javascript JS - 使用当前窗口大小设置窗口高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14505224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JS - set window height using current window size
提问by cloggy
I have some CSS that needs the body to have a height set, but this needs to be done depending on the user.
我有一些 CSS 需要身体设置高度,但这需要根据用户来完成。
I have made some code that kind of works - it calculates the window height but it's not changing the body height. What am I doing wrong?
我已经编写了一些有效的代码 - 它计算窗口高度但它不会改变主体高度。我究竟做错了什么?
function setWindowHeight(){
var windowHeight = window.innerHeight;
document.getElementsByTagName('body').style.height = windowHeight + "px";
}
采纳答案by Erick Ribeiro
You need to add an eventListener, and you don't need to use the getElementsByTagName because has only 1 body tag:
您需要添加一个 eventListener,并且不需要使用 getElementsByTagName 因为只有 1 个 body 标记:
function setWindowHeight(){
var windowHeight = window.innerHeight;
document.body.style.height = windowHeight + "px";
console.log(document.body.style.height);
}
window.addEventListener("resize",setWindowHeight,false);
Or, if you want to use, you can do this:
或者,如果你想使用,你可以这样做:
function setWindowHeight(){
var windowHeight = window.innerHeight;
document.getElementsByTagName('body')[0].style.height = windowHeight + "px";
console.log(document.body.style.height);
//---------------------------------------′
//will get the first element tagged body
}
window.addEventListener("resize",setWindowHeight,false);
EDIT (Changed the code above):you can check the value in the Firefox Console. Open it(CTRL + SHIFT + K) and resize the window, you will see the event resizebe fired when you do it.
编辑(更改上面的代码):您可以在 Firefox 控制台中检查该值。打开它(CTRL + SHIFT + K)并调整窗口大小,您将看到在执行此操作时会触发事件调整大小。
回答by A.T.
try this may work
document.getElementsByTagName('body').height = windowHeight + "px";

