相当于在vanillajs中将html和body height设置为窗口高度 [英] Equivalent to setting html and body height to window height in vanillajs
问题描述
这个javascript行的vanilla js中的等价代码是什么?
What is the equivalent code in vanilla js to this line of javascript?
$('html, body, #wrapper').height($(window).height());
这是我的尝试,但它似乎没有正常工作(似乎没有设置所有3个元素的任何高度):
This was my attempt, but it doesn't seem to be working properly (it seems to not set any height on all 3 elements at all):
var w=window,d=document,
e=d.documentElement,
g=d.getElementsByTagName("body")[0];
x=w.innerWidth || e.clientWidth || g.clientWidth,y=w.innerHeight || e.clientHeight || g.clientHeight;
document.querySelector("html").clientHeight = g.clientHeight = document.getElementById("wrapper").clientHeight = y;
推荐答案
您可以使用 Window#innerHeight ,使用 Document#querySelectorAll 。要迭代 elementList
返回 querySelectorAll
,我们将使用 NodeList#forEach (如果不支持,则将元素列表转换为数组 - 见下文),并设置每个元素的高度:
You can get the height of the window using Window#innerHeight, select the target using Document#querySelectorAll. To iterate the elementList
that querySelectorAll
returns, we'll use NodeList#forEach (if not supported convert the element list to an array - see below), and set the height on each element:
var height = window.innerHeight + 'px';
document.querySelectorAll('html, body, #wrapper').forEach(function(el) {
el.style.height = height;
});
#wrapper {
background: red;
}
<div id="wrapper"></div>
如果您需要将元素列表转换为arr ay:
If you need to convert the the element list to an array:
[].slice.call(document.querySelectorAll('html, body, #wrapper'), 0)
或
Array.from(document.querySelectorAll('html, body, #wrapper'))
这篇关于相当于在vanillajs中将html和body height设置为窗口高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!