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

后端 未结 25 2056
爱一瞬间的悲伤
爱一瞬间的悲伤 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:10

    Store the previous scroll location, then see if the new one is greater than or less than that.

    Here's a way to avoid any global variables (fiddle available here):

    (function () {
        var previousScroll = 0;
    
        $(window).scroll(function(){
           var currentScroll = $(this).scrollTop();
           if (currentScroll > previousScroll){
               alert('down');
           } else {
              alert('up');
           }
           previousScroll = currentScroll;
        });
    }()); //run this anonymous function immediately
    

提交回复
热议问题