当前位置:网站首页>js监听页面或元素scroll事件,滚动到底部或顶部
js监听页面或元素scroll事件,滚动到底部或顶部
2022-06-24 19:44:00 【彭世瑜】

基本原理:
1、滚动到底部
元素的滚动距离 + 元素的可视距离 == 元素的滚动条总距离
2、滚动到顶部
元素的滚动距离 == 0
监听页面滚动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Scroll Demo</title>
</head>
<body>
<style> .box {
height: 5000px; text-align: center; } </style>
<div class="box" id="box">打开控制台查看</div>
<!-- 引入节流方法 -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/umd/index.min.js"></script>
<script> // 滚动方向枚举值 const DIRECTION_ENUM = {
DOWN: "down", UP: "up", }; // 距离顶部或底部的阈值 const threshold = 20; // 记录前一个滚动位置 let beforeScrollTop = 0; function handleScroll() {
// 距顶部 var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; // 可视区高度 var clientHeight = document.documentElement.clientHeight || document.body.clientHeight; // 滚动条总高度 var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight; // 打印数值 console.table([ {
label: "距顶部", value: scrollTop, }, {
label: "可视区高度", value: clientHeight, }, {
label: "滚动条总高度", value: scrollHeight, }, {
label: "距顶部 + 可视区高度", value: scrollTop + clientHeight, }, ]); // 确定滚动方向 let direction = DIRECTION_ENUM.DOWN; if (beforeScrollTop > scrollTop) {
direction = DIRECTION_ENUM.UP; } // 通过滚动方向判断是触底还是触顶 if (direction == DIRECTION_ENUM.DOWN) {
// 滚动触底 if (scrollTop + clientHeight + threshold >= scrollHeight) {
console.log("滚动触底"); } } else {
// 滚动到顶部 if (scrollTop <= threshold) {
console.log("滚动到顶部"); } } beforeScrollTop = scrollTop; } // 滚动节流 const throttleHandleScroll = throttleDebounce.throttle( 1000, handleScroll ); // 监听滚动 window.addEventListener('scroll', throttleHandleScroll); </script>
</body>
</html>
同理,也可以监听元素的滚动
<style> .box-wrap {
height: 500px; overflow-y: auto; } .box {
height: 5000px; text-align: center; } </style>
<div class="box-wrap" id="box">
<div class="box">打开控制台查看</div>
</div>
<script> // 监听滚动 let box = document.querySelector("#box"); box.addEventListener("scroll", function (e) {
let scrollTop = e.target.scrollTop; let clientHeight = e.target.clientHeight; let scrollHeight = e.target.scrollHeight; // 打印数值 console.table([ {
label: "距顶部", value: scrollTop, }, {
label: "可视区高度", value: clientHeight, }, {
label: "滚动条总高度", value: scrollHeight, }, {
label: "距顶部 + 可视区高度", value: scrollTop + clientHeight, }, ]); }); </script>
判断触底需要注意的点:
- 滚动时需要区分向上滚动还是向下滚动
- 滚动时可以设置一个阈值,并非完全触底或触顶才触发
- 滚动事件需要做节流操作,以免短时间内被多次触发
在线Demo
边栏推荐
- R language uses the multinom function of NNET package to build an unordered multi classification logistic regression model, and uses exp function and coef function to obtain the corresponding odds rat
- 还在用 SimpleDateFormat 做时间格式化?小心项目崩掉
- 慕思股份深交所上市:靠床垫和“洋老头”走红 市值224亿
- Construction equipment [6]
- 376. Tâches mécaniques
- Ningde times will increase RMB 45billion: Hillhouse subscribes RMB 3billion and Zeng Yuqun still controls 23% of the equity
- R语言使用glm函数构建泊松对数线性回归模型处理三维列联表数据构建饱和模型、使用summary函数获取模型汇总统计信息、解读模型系数交互作用及其显著性
- 【UVM入门 ===> Episode_8 】~ Sequence 和 Sequencer、Sequence 层次化
- [basic knowledge] ~ half adder & full adder
- 【js】-【树】-学习笔记
猜你喜欢

From client to server

Simpledateformat concrete classes for formatting and parsing dates

【js】-【链表-应用】-学习笔记

选择类排序法

Actipro WPF Controls 2022.1.2

File contains vulnerability issues

伪原创智能改写api百度-收录良好

RT thread uses RT kprintf

What good smart home brands in China support homekit?

Record the range of data that MySQL update will lock
随机推荐
从客户端到服务器
OpenSSL SSL_read: Connection was reset, errno 10054
websocket长链接压测
Bubble sort
Dig deep into MySQL - resolve the clustered index / secondary index / federated index of InnoDB storage engine
Simpledateformat concrete classes for formatting and parsing dates
第六章 网络学习相关技巧5(超参数验证)
No main manifest attribute in jar
R语言使用epiDisplay包的aggregate函数将数值变量基于因子变量拆分为不同的子集,计算每个子集的汇总统计信息、自定义FUN参数为多个统计量函数名称的列表计算多个统计量
文件包含漏洞问题
監聽 Markdown 文件並熱更新 Next.js 頁面
372. 棋盘覆盖
Detailed explanation of online group chat and dating platform project (servlet implementation)
R language dplyr package group_ By function and summarize_ The at function calculates the dataframe to calculate the number of counts and the mean value of different groups (summary data by category v
What good smart home brands in China support homekit?
Notes for laravel model
golang map clear
Basic data type
R语言使用MASS包的polr函数构建有序多分类logistic回归模型、使用exp函数、confint函数、coef函数获取模型中每个变量(自变量改变一个单位)对应的优势比的置信区间
Binary lookup array subscript