2017-10-13 81 views
3

在這行javascript中,vanilla js中的等效代碼是什麼?相當於將html和身高設置爲vanillajs中的窗口高度

$('html, body, #wrapper').height($(window).height()); 

這是我的嘗試,但它似乎沒有正常工作(這似乎不設置任何高度上的所有所有3個元素):

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; 

回答

3

你可以得到高度窗口使用Window#innerHeight,請使用Document#querySelectorAll選擇目標。要遍歷elementListquerySelectorAll回報,我們將使用NodeList#forEach(如果不支持的元素列表轉換爲數組 - 見下文),並設置高度每個元素:

var height = window.innerHeight + 'px'; 
 

 
document.querySelectorAll('html, body, #wrapper').forEach(function(el) { 
 
    el.style.height = height; 
 
});
#wrapper { 
 
    background: red; 
 
}
<div id="wrapper"></div>

如果你需要的元素列表轉換爲數組:

[].slice.call(document.querySelectorAll('html, body, #wrapper'), 0) 

Array.from(document.querySelectorAll('html, body, #wrapper')) 
相關問題