文章目录
作为前端开发者,掌握页面滚动方向的检测技术对于创建动态交互体验至关重要。本文将深入探讨JavaScript中判断滚动方向的多种方法,并提供专业且实用的实现方案。
滚动方向检测的核心原理
在深入具体实现前,我们需要理解滚动检测的基本原理:
// 基本概念:比较当前和上一次的滚动位置
let lastScrollPosition = window.scrollY;
window.addEventListener('scroll', () => {
const currentScrollPosition = window.scrollY;
if (currentScrollPosition > lastScrollPosition) {
// 向下滚动
} else {
// 向上滚动
}
lastScrollPosition = currentScrollPosition;
});
方法一:基于滚动位置比较(最常用)
基础实现
let lastScrollTop = 0;
window.addEventListener('scroll', function() {
const currentScrollTop = window.pageYOffset || document.documentElement.scrollTop;
if (currentScrollTop > lastScrollTop) {
console.log('向下滚动');
} else if (currentScrollTop < lastScrollTop) {
console.log('向上滚动');
}
lastScrollTop = currentScrollTop;
});
性能优化版(使用requestAnimationFrame)
let lastScrollTop = 0;
let ticking = false;
window.addEventListener('scroll', function() {
if (!ticking) {
window.requestAnimationFrame(function() {
const currentScrollTop = window.pageYOffset || document.documentElement.scrollTop;
if (currentScrollTop > lastScrollTop) {
console.log('向下滚动');
} else if (currentScrollTop < lastScrollTop) {
console.log('向上滚动');
}
lastScrollTop = currentScrollTop;
ticking = false;
});
ticking = true;
}
});
优点:
- 实现简单直观
- 兼容性好(支持IE9+)
- 适用于所有滚动场景
缺点:
- 需要处理高频事件
- 在快速滚动时可能有细微延迟
方法二:使用Wheel事件(针对鼠标/触控板)
window.

3118

被折叠的 条评论
为什么被折叠?



