在JavaScript中获取页面高度通常涉及到window.innerHeight
、document.documentElement.clientHeight
或者document.body.scrollHeight
这几个属性,具体使用哪个取决于你想要获取的高度类型。
window.innerHeight
:这个属性返回浏览器窗口的视口(viewport)高度,包括滚动条(如果存在的话)。document.documentElement.clientHeight
:这个属性返回HTML文档的根元素(<html>
)的可视区域高度,不包括滚动条。document.body.scrollHeight
:这个属性返回整个文档的高度,包括由于溢出而不可见的内容。window.innerHeight
或document.documentElement.clientHeight
。document.body.scrollHeight
。// 获取浏览器窗口的视口高度
var viewportHeight = window.innerHeight;
console.log("Viewport Height: " + viewportHeight);
// 获取HTML文档的可视区域高度
var documentHeight = document.documentElement.clientHeight;
console.log("Document Height: " + documentHeight);
// 获取整个文档的高度
var scrollHeight = document.body.scrollHeight;
console.log("Scroll Height: " + scrollHeight);
transform
属性,可能会影响到scrollHeight
的计算。如果你发现获取的页面高度不准确,可以尝试以下方法:
window.onload
事件中,或者使用DOMContentLoaded
事件。window.onload = function() {
var height = document.documentElement.clientHeight;
console.log(height);
};
margin
、padding
、border
或者box-sizing
属性。resize
事件来动态获取新的高度。window.addEventListener('resize', function() {
var height = window.innerHeight;
console.log(height);
});
ResizeObserver
API来监听元素尺寸的变化。var ro = new ResizeObserver(entries => {
for (let entry of entries) {
const height = entry.contentRect.height;
console.log(height);
}
});
ro.observe(document.body);
确保在使用这些方法时,考虑到不同浏览器的兼容性问题,并进行相应的适配。
领取专属 10元无门槛券
手把手带您无忧上云