我在找这样的东西:

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

什么好主意吗?


当前回答

存储之前的滚动位置,然后查看新的滚动位置是否大于或小于该位置。

这里有一个避免任何全局变量的方法(在这里可以找到):

(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

其他回答

保持超级简单:

jQuery事件监听器

$(window).on('wheel', function(){
  whichDirection(event);
});

香草JavaScript事件监听器

if(window.addEventListener){
  addEventListener('wheel', whichDirection, false);
} else if (window.attachEvent) {
  attachEvent('wheel', whichDirection, false);
}

功能不变:

function whichDirection(event){
  console.log(event + ' WheelEvent has all kinds of good stuff to work with');
  var scrollDirection = event.deltaY;
  if(scrollDirection === 1){
    console.log('meet me at the club, going down', scrollDirection);
  } else if(scrollDirection === -1) {
    console.log('Going up, on a tuesday', scrollDirection);
  }
}

我在这里写了一篇更深入的文章 ​​​​​​​

我在这里看到了许多版本的好答案,但似乎有些人有跨浏览器的问题,所以这是我的解决方案。

我已经成功地使用这个方法在FF, IE和Chrome中检测方向…我没有在safari中测试它,因为我通常使用windows。

$("html, body").bind({'mousewheel DOMMouseScroll onmousewheel touchmove scroll': 
    function(e) {
        if (e.target.id == 'el') return;
        e.preventDefault();
        e.stopPropagation();

        //Determine Direction
        if (e.originalEvent.wheelDelta && e.originalEvent.wheelDelta >= 0) {
            //Up
            alert("up");

        } else if (e.originalEvent.detail && e.originalEvent.detail <= 0) {
            //Up
            alert("up");

        } else {
            //Down
            alert("down");
        }
    }
});

请记住,我也使用这个来停止任何滚动,所以如果你想要滚动仍然发生,你必须删除e.preventDefault();e.stopPropagation ();

这段代码在IE, Firefox, Opera和Chrome中工作良好:

$(window).bind('wheel mousewheel', function(event) {
      if (event.originalEvent.deltaY >= 0) {
          console.log('Scroll down');
      }
      else {
          console.log('Scroll up');
      }
  });

'wheel mousewheel'和属性delay必须在bind()函数中使用。

记住:出于安全考虑,你的用户必须更新他们的系统和浏览器。2018年,“我有ie7”的借口是一派胡言。我们必须教育用户。

祝你有愉快的一天。

您可以同时使用滚动和鼠标滚轮选项来跟踪上下移动一次。

 $('body').bind('scroll mousewheel', function(event) {

if (event.originalEvent.wheelDelta >= 0) {
      console.log('moving down');   
    }
    else {
      console.log('moving up'); 
    }
});

你也可以用window代替body。

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