怎么获取当前页面高度
时间: 2023-11-13 16:06:04 浏览: 85
获取当前页面高度也有多种方法,其中一种方法是使用JavaScript的 `document` 对象的 `body` 或 `documentElement` 属性的 `scrollHeight` 或 `clientHeight` 属性来获取当前页面的高度。具体步骤如下:
1. 在JavaScript代码中使用 `document.body.scrollHeight` 或 `document.documentElement.scrollHeight` 来获取当前页面的高度:
```javascript
const pageHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
```
这里使用了 `Math.max` 函数来获取 `body` 和 `documentElement` 的 `scrollHeight` 属性中的最大值,因为有些浏览器中,`body` 和 `documentElement` 的 `scrollHeight` 属性可能不相等,而我们需要获取的是两者之间的最大值。
2. 如果需要获取当前可见部分的页面高度,可以使用 `document.body.clientHeight` 或 `document.documentElement.clientHeight` 来获取:
```javascript
const visibleHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight);
```
这里同样使用了 `Math.max` 函数来获取 `body` 和 `documentElement` 的 `clientHeight` 属性中的最大值,因为有些浏览器中,`body` 和 `documentElement` 的 `clientHeight` 属性可能不相等,而我们需要获取的是两者之间的最大值。
另外,如果要实时获取页面高度,可以使用 `window` 对象的 `resize` 事件来监听窗口大小的变化,并在事件触发时重新计算页面高度。
例如:
```javascript
window.addEventListener('resize', function() {
const pageHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
const visibleHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight);
console.log('当前页面高度为:' + pageHeight);
console.log('当前可见部分页面高度为:' + visibleHeight);
});
```
这样在浏览器窗口大小改变时,就会自动更新页面高度并输出到控制台中。
阅读全文
相关推荐













