方法一:使用变量记录上次滚动位置
let
window.addEventListener('scroll', function() {
const currentScroll = window.pageYOffset || document.documentElement.scrollTop;
if (currentScroll > lastScrollTop) {
// 向下滚动
console.log('向下滚动');
} else if (currentScroll < lastScrollTop) {
// 向上滚动
console.log('向上滚动');
}
lastScrollTop = currentScroll <= 0 ? 0 : currentScroll;
}, false);
方法二:使用更精确的 delta 值判断
let
window.addEventListener('scroll', function() {
const currentScrollPosition = window.pageYOffset;
const scrollDelta = currentScrollPosition - lastScrollPosition;
if (scrollDelta > 0) {
console.log('向下滚动', scrollDelta);
} else if (scrollDelta < 0) {
console.log('向上滚动', scrollDelta);
}
lastScrollPosition = currentScrollPosition;
});
方法三:使用 requestAnimationFrame 优化性能
let
let ticking = false;
window.addEventListener('scroll', function() {
lastKnownScrollPosition = window.scrollY;
if (!ticking) {
window.requestAnimationFrame(function() {
const current = lastKnownScrollPosition;
const direction = current > (lastKnownScrollPosition || 0) ? 'down' : 'up';
console.log(direction);
ticking = false;
});
ticking = true;
}
});