监听页面向上向下滚动事件

需求

希望在页面向下滚动时则隐藏"返回顶部"按钮,否则显示。
以下将滚动代码整理出来scrollEvent()方法
(适用于滚轮滚动、键盘上下滚动、滚动条滚动)

代码

/* 监听页面向上向下滚动事件 */
function scrollEvent() {
  window.onscroll = function (e) {
    scrollFunc();
    if (scrollDirection == 'down') {
      //页面向下滚动要做的事情
    } else if (scrollDirection == 'up') {
      //页面向上滚动要做的事情
    }
  }
}

var scrollAction = {
    x: 'undefined',
    y: 'undefined'
  },
  scrollDirection;

function scrollFunc() {
  if (typeof scrollAction.x == 'undefined') {
    scrollAction.x = window.pageXOffset;
    scrollAction.y = window.pageYOffset;
  }
  var diffX = scrollAction.x - window.pageXOffset;
  var diffY = scrollAction.y - window.pageYOffset;
  if (diffX < 0) {
    // Scroll right
    scrollDirection = 'right';
  } else if (diffX > 0) {
    // Scroll left
    scrollDirection = 'left';
  } else if (diffY < 0) {
    // Scroll down
    scrollDirection = 'down';
  } else if (diffY > 0) {
    // Scroll up
    scrollDirection = 'up';
  } else {
    // First scroll event
  }
  scrollAction.x = window.pageXOffset;
  scrollAction.y = window.pageYOffset;
}
posted @ 2020-09-23 10:54  ZerlinM  阅读(1529)  评论(0编辑  收藏  举报