我在找这样的东西:

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

什么好主意吗?


当前回答

在滚动的元素的.data()中存储一个增量,然后就可以测试滚动到达顶部的次数。

其他回答

var tempScrollTop, currentScrollTop = 0; 

$(window).scroll(function(){ 

   currentScrollTop = $("#div").scrollTop(); 

   if (tempScrollTop > currentScrollTop ) {
       // upscroll code
   }
  else if (tempScrollTop < currentScrollTop ){
      // downscroll code
  }

  tempScrollTop = currentScrollTop; 
} 

或者使用鼠标滚轮扩展,见这里。

在元素的.data()中,您可以存储JSON和测试值来启动事件

{ top : 1,
   first_top_event: function(){ ...},
   second_top_event: function(){ ...},
   third_top_event: function(){ ...},
   scroll_down_event1: function(){ ...},
   scroll_down_event2: function(){ ...}
}

为了忽略页面顶部和底部的任何snap / momentum / bounce back,这里是Josiah接受的答案的修改版本:

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;
});

如果你只是想知道你是使用指针设备(鼠标或跟踪板)向上滚动还是向下滚动,你可以使用wheel事件的delay属性。

$('.container').on('wheel', function(event) { if (event.originalEvent.deltaY > 0) { $('.result').append('Scrolled down!<br>'); } else { $('.result').append('Scrolled up!<br>'); } }); .container { height: 200px; width: 400px; margin: 20px; border: 1px solid black; overflow-y: auto; } .content { height: 300px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div class="content"> Scroll me! </div> </div> <div class="result"> <p>Action:</p> </div>

为什么没有人使用滚动的jQuery返回的事件对象?

$window.on('scroll', function (event) {
    console.group('Scroll');
    console.info('Scroll event:', event);
    console.info('Position:', this.pageYOffset);
    console.info('Direction:', event.originalEvent.dir); // Here is the direction
    console.groupEnd();
});

我使用铬,我没有检查其他浏览器,如果他们有dir属性。