前端技术

JavaScript 判断页面垂直滚动方向

let theScrollY = 0
let theScrollOrient ='top'

function getScrollOrient() {
  // 初始化页面位置
  if ( theScrollY == 0) {
    theScrollY = window.scrollY
  }

  // 判断滚动方向
  let diffY = theScrollY - window.scrollY
  if ( diffY < 0 ) {
    theScrollOrient = 'down'
  } else if ( diffY > 0 ) {
    theScrollOrient = 'up'
  }
  if ( window.scrollY == 0 ) {
    theScrollOrient = 'top'
  }

  // 重新赋值滚动位置
  theScrollY = window.scrollY
}

window.addEventListener('scroll', () => {
  getScrollOrient()
  if( theScrollOrient == 'down' ){
  // 执行向下滚动时的语句
    console.log(theScrollOrient)
  }
  else if( theScrollOrient == 'up' ){
  // 执行向上滚动时的语句
    console.log(theScrollOrient)
  } else (
  // 执行回到顶部时的语句
    console.log(theScrollOrient)
  )
})

PUJI Design 朴及设计 (c) 2024. 沪ICP备17052229号