判断页面滚动方向的方法

101 阅读1分钟

方法一:使用变量记录上次滚动位置


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 值判断


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 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;
  }
});