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

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

    I had problems with elastic scrolling (scroll bouncing, rubber-banding). Ignoring the down-scroll event if close to the page top worked for me.

    var position = $(window).scrollTop();
    $(window).scroll(function () {
        var scroll = $(window).scrollTop();
        var downScroll = scroll > position;
        var closeToTop = -120 < scroll && scroll < 120;
        if (downScroll && !closeToTop) {
            // scrolled down and not to close to top (to avoid Ipad elastic scroll-problems)
            $('.top-container').slideUp('fast');
            $('.main-header').addClass('padding-top');
        } else {
            // scrolled up
            $('.top-container').slideDown('fast');
            $('.main-header').removeClass('padding-top');
        }
        position = scroll;
    });
    

提交回复
热议问题