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

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

    To ignore any snap / momentum / bounce back at the top and bottom of the page, here is a modified version of Josiah's accepted answer:

    var prevScrollTop = 0;
    $(window).scroll(function(event){
    
        var scrollTop = $(this).scrollTop();
    
        if ( scrollTop < 0 ) {
            scrollTop = 0;
        }
        if ( scrollTop > $('body').height() - $(window).height() ) {
            scrollTop = $('body').height() - $(window).height();
        }
    
        if (scrollTop >= prevScrollTop && scrollTop) {
            // scrolling down
        } else {
            // scrolling up
        }
    
        prevScrollTop = scrollTop;
    });
    

提交回复
热议问题