检测向上滚动不正常

时间:2017-04-02 11:58:48

标签: javascript jquery

我试图使用此代码来获取滚动方向问题是向上滚动检测不顺利

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

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

});

这里是结果enter image description here的屏幕截图,它显示向上滚动然后向下滚动但我没有向下滚动

1 个答案:

答案 0 :(得分:0)

你有太多的事件限制。

试试这段代码,唯一的区别是我在div上使用它。

$('div').bind('mousewheel', function(event) {

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

});

这是一个有效的JS小提琴:

https://jsfiddle.net/r1sjv2tv/

编辑:上述答案有效,尽管只在使用滚轮滚动时。 但是,窗口也可以用鼠标滚动。如果你也要处理它,它会变得更复杂。

我已经制作了一个侦听onscroll事件的解决方案,只是简单地将当前的scrolltop位置与最后一个scrolltop位置进行比较,以确定滚动的方向。

$('div').bind('scroll', function(event) {

  if ($(this).scrollTop() < $(this).data('last-scroll')) {
    console.log('scroll up');
  } else {
    console.log('scroll down');
  }

  $(this).data('last-scroll',$(this).scrollTop());
});

这与原始事件触发器无关。

请看小提琴:

https://jsfiddle.net/r1sjv2tv/2/