PHP前端开发

js如何获取网页高度

百变鹏仔 3天前 #JavaScript
文章标签 高度
在 javascript 中,获取网页高度有四种方法:document.documentelement.clientheight:可视高度,不含滚动条或菜单栏。document.body.scrollheight:总高度,包含已滚动元素。math.max(documentelement.clientheight, body.scrollheight):获取最大高度。window.innerheight:可视高度,包含已滚动元素。

如何使用 JavaScript 获取网页高度

网页高度指从网页顶部到底部的垂直距离,它可以帮助开发人员了解网页的大小以及内容的长度。在 JavaScript 中,有几种方法可以获取网页高度。

1. 使用 document.documentElement.clientHeight

const pageHeight = document.documentElement.clientHeight;

clientHeight 属性返回浏览器窗口的可视高度,不包括滚动条或菜单栏等元素。

2. 使用 document.body.scrollHeight

const pageHeight = document.body.scrollHeight;

scrollHeight 属性返回网页的总高度,包括页面中所有已滚动元素的高度。

3. 使用 Math.max

如果需要获取最大高度,则可以使用 Math.max 函数:

const pageHeight = Math.max(  document.documentElement.clientHeight,  document.body.scrollHeight);

4. 使用 window.innerHeight

也可以使用 window.innerHeight 属性,它返回浏览器窗口的可视高度,包括任何已滚动元素:

const pageHeight = window.innerHeight;

示例

以下是如何使用上述方法之一在控制台中获取网页高度:

console.log(document.documentElement.clientHeight); // 获取可视高度console.log(document.body.scrollHeight); // 获取总高度console.log(Math.max(document.documentElement.clientHeight, document.body.scrollHeight)); // 获取最大高度console.log(window.innerHeight); // 获取可视高度(包括已滚动元素)