如何使用 JavaScript 判断页面底部是否可见?
在本教程中,我们将检查页面的底部部分是否对用户可见。我们可以通过使用**窗口**的高度和**滚动**窗口的高度来实现此功能。要编写此代码,我们需要理解 JavaScript 的三种方法,如下所示:
**scrollY** - 它是窗口的只读属性,返回文档垂直滚动的像素数。
window.scrollY
**scrollHeight** - 它是 HTML DOM 元素和窗口的只读属性。它返回元素内容的高度,包括不可见的内容。
element.scrollHeight
**clientHeight** - 它也是只读属性,以像素为单位返回元素的可视高度,包括内边距,但不包括边框、滚动条或外边距。
element.clientHeight window.clientHeight
**注意** - 上述三种方法都以像素为单位测量元素的值。
语法
以下是检查页面底部是否可见的条件的语法。
document.documentElement.clientHeight + window.scrollY >=(document.documentElement.scrollHeight ||document.documentElement.clientHeight);
如果上述条件为真,则页面底部将可见。
方法
我们检查 *clientHeight* 和 *scrollY* 的和是否大于或等于 *scrollHeight* 或 *clientHeight*。如果此条件为真,则页面底部将可见。因此,我们定义一个函数,如果满足条件则返回 true。
示例
使用 *documentElement* 的 *clientHeight* 属性
在下面的程序中,我们检查页面底部是否可见。我们使用 *documentElement* 的 *clientHeight* 属性检查语法部分中定义的条件。
<!DOCTYPE html>
<html>
<head>
<title>Example - Bottom Visible JavaScript</title>
</head>
<body>
<div style="margin-bottom:100px;">
<h3>Checking if bottom of page is visible</h3>
<p id = "bottom"> Is bottom of the Page visible?<br></p>
</div>
<div> You reached to the bottom of the page.</div>
<script>
const bottomVisible = () =>
document.documentElement.clientHeight + window.scrollY >=
(document.documentElement.scrollHeight ||
document.documentElement.clientHeight);
console.log(bottomVisible());
document.getElementById("bottom").innerHTML += bottomVisible()
</script>
</body>
</html>在上面的代码中,我们比较两个值,一个是 client height 和 scrollY 的和,另一个是 scroll height 和 client height 的或运算。当 client height 和 scrollY 的和大于或等于 scroll height 和 client height 的或运算时,result 值为 true,这表示页面底部可见。
示例
使用 *window* 接口的 *clientHeight* 属性
在下面的程序中,我们检查页面底部是否可见。我们使用 *window* 接口的 *clientHeight* 属性检查语法部分中定义的条件。
<!DOCTYPE html>
<html>
<head>
<title>Example - Bottom Visible JavaScript</title>
</head>
<body>
<div style="margin-bottom:100px;">
<h3>Checking if bottom of page is visible</h3>
<p id = "bottom"> Is bottom of the Page visible?<br></p>
</div>
<div> You reached to the bottom of the page.</div>
<script>
const bottomVisible = () =>
window.innerHeight + window.scrollY >=(document.documentElement.scrollHeight || window.innerHeight);
console.log(bottomVisible());
document.getElementById("bottom").innerHTML += bottomVisible()
</script>
</body>
</html>示例
页面底部不可见
在下面的程序中,我们将 div 的底部边距设置得非常高,以至于页面底部不可见。
<html>
<head>
<title>Example - Bottom Visible JavaScript</title>
</head>
<body>
<div style="margin-bottom:2500px;">
<h3>The bottom of page not visible</h3>
<p id = "bottom"> Is bottom of the Page visible?<br></p>
<p id> <br> Please scroll down to reach the bottom...</p>
</div>
<div> You reached to the bottom of the page.</div>
<script>
const bottomVisible = () =>
window.clientHeight + window.scrollY >=(document.documentElement.scrollHeight || window.clientHeight);
console.log(bottomVisible());
document.getElementById("bottom").innerHTML += bottomVisible()
</script>
</body>
</html>
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP