How can I determine the direction of a jQuery scroll event?

后端 未结 25 1872
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 22:24

I\'m looking for something to this effect:

$(window).scroll(function(event){
   if (/* magic code*/ ){
       // upscroll code
   } else {
      // downscrol         


        
25条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-21 23:07

    Keep it super simple:

    jQuery Event Listener Way:

    $(window).on('wheel', function(){
      whichDirection(event);
    });
    

    Vanilla JavaScript Event Listener Way:

    if(window.addEventListener){
      addEventListener('wheel', whichDirection, false);
    } else if (window.attachEvent) {
      attachEvent('wheel', whichDirection, false);
    }
    

    Function Remains The Same:

    function whichDirection(event){
      console.log(event + ' WheelEvent has all kinds of good stuff to work with');
      var scrollDirection = event.deltaY;
      if(scrollDirection === 1){
        console.log('meet me at the club, going down', scrollDirection);
      } else if(scrollDirection === -1) {
        console.log('Going up, on a tuesday', scrollDirection);
      }
    }
    

    I wrote a more indepth post on it here ​​​​​​​

提交回复
热议问题