当前位置:网站首页>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
边栏推荐
- 慕思股份深交所上市:靠床垫和“洋老头”走红 市值224亿
- R语言dplyr包select函数将dataframe数据中的指定数据列移动到dataframe数据列中的第一列(首列)
- The dplyr package select function of R language moves the specified data column in the dataframe data to the first column (the first column) in the dataframe data column
- InnoDB, the storage engine of MySQL Architecture Principle_ Redo log and binlog
- 7-6 铺设油井管道
- 257. detention of offenders
- Financial management [6]
- Huawei machine learning service speech recognition function enables applications to paint "sound" and color
- R语言使用glm函数构建泊松对数线性回归模型处理三维列联表数据构建饱和模型、使用summary函数获取模型汇总统计信息、解读模型系数交互作用及其显著性
- 监听 Markdown 文件并热更新 Next.js 页面
猜你喜欢

Record the range of data that MySQL update will lock

基于三维GIS开发的水电工程建设方案

Dig deep into MySQL - resolve the clustered index / secondary index / federated index of InnoDB storage engine

Fibonacci

Still using simpledateformat for time formatting? Be careful of project collapse

Actipro WPF Controls 2022.1.2

安装IBM CPLEX学术版 academic edition | conda 安装 CPLEX

Chapter VI skills related to e-learning 5 (super parameter verification)

Ningde times will increase RMB 45billion: Hillhouse subscribes RMB 3billion and Zeng Yuqun still controls 23% of the equity

Actipro WPF Controls 2022.1.2
随机推荐
Whereabouts computer desktop small arrow
22map introduction and API
7-9 寻宝路线
379. hide and seek
libnum库简单使用(进制字符串转换)
六大行数据治理现状盘点:治理架构、数据标准与数据中台(2022.04)
当初吃土建起来的“中台”,现在为啥不香了?
斐波那契
golang convert json string to map
websocket长链接压测
【js】-【字符串-应用】- 学习笔记
Laravel study notes
去处电脑桌面小箭头
golang convert map to json string
[JS] - [tree] - learning notes
Actipro WPF Controls 2022.1.2
Building Survey [2]
Redis source code analysis skip list
Detailed explanation of online group chat and dating platform project (servlet implementation)
Blogs personal blog test point (manual test)