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

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

    This is an optimal solution for detecting the direction just when the user end scrolling.

    var currentScrollTop = 0 ;
    
    $(window).bind('scroll', function () {     
    
        scrollTop = $(this).scrollTop();
    
        clearTimeout($.data(this, 'scrollTimer'));
        $.data(this, 'scrollTimer', setTimeout(function() {
    
            if(scrollTop > currentScrollTop){
                // downscroll code
                $('.mfb-component--bl').addClass('mfbHide');
            }else{
                // upscroll code
                $('.mfb-component--bl').removeClass('mfbHide');
            }
            currentScrollTop = scrollTop;
    
        }, 250));
    
    });
    

提交回复
热议问题