如何确定jQuery滚动事件的方向?

375

我正在寻找类似于这种效果的东西:

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

有什么想法吗?


对于那些在弹性滚动方面遇到问题的人,请使用此答案 https://dev59.com/7Ww05IYBdhLWcg3wkivX - Timothy Dalton
1
现在最容易使用的是wheel事件:https://dev59.com/7Ww05IYBdhLWcg3wkivX#33334461。 - Shikkediel
25个回答

3

使用此功能来查找滚动方向。仅用于查找垂直滚动的方向。支持所有跨浏览器。

    var scrollableElement = document.getElementById('scrollableElement');

    scrollableElement.addEventListener('wheel', findScrollDirectionOtherBrowsers);

    function findScrollDirectionOtherBrowsers(event){
        var delta;

        if (event.wheelDelta){
            delta = event.wheelDelta;
        }else{
            delta = -1 * event.deltaY;
        }

        if (delta < 0){
            console.log("DOWN");
        }else if (delta > 0){
            console.log("UP");
        }

    }

Example


3
var tempScrollTop, currentScrollTop = 0; 

$(window).scroll(function(){ 

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

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

  tempScrollTop = currentScrollTop; 
} 

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


3

我已经看到很多关于此问题的好答案,但似乎有些人会遇到跨浏览器的问题,这是我的解决方法。

我已经成功地在FF、IE和Chrome中使用这个方法来检测方向...由于我通常使用Windows操作系统,所以我没有在Safari中进行测试。

$("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();


1
总是在安卓GS5上返回下降。 - SISYN
这个很棒!我在IE上遇到了顶票答案的问题。这个没有那个问题!+1。 - Radmation

3
你可以确定鼠标滚轮的方向。
$(window).on('mousewheel DOMMouseScroll', function (e) {
    var delta = e.originalEvent.wheelDelta ? 
                   e.originalEvent.wheelDelta : -e.originalEvent.detail;

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

2

请保持简单:

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

我在这里写了一篇更深入的文章,关于IT技术方面的内容。您可以通过这里阅读。

使用jQuery版本是否需要jquery-wheel? - Hastig Zusammenstellen
1
jquery-wheel不是@HastigZusammenstellen所需的。 - CR Rollyson

2

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

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

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

您可以将“body”替换为(window)。


在Chrome中似乎工作正常,但在FF(55.0.2,Ubuntu)中不行。 - Hastig Zusammenstellen

1

You can use this as well

$(document).ready(function(){

  var currentscroll_position = $(window).scrollTop();
$(window).on('scroll', function(){
Get_page_scroll_direction();
});

function Get_page_scroll_direction(){
  var running_scroll_position = $(window).scrollTop();
  if(running_scroll_position > currentscroll_position) {
      
      $('.direction_value').text('Scrolling Down Scripts');

  } else {
       
       $('.direction_value').text('Scrolling Up Scripts');

  }
  currentscroll_position = running_scroll_position;
}

});
.direction_value{
  position: fixed;
  height: 30px;
  background-color: #333;
  color: #fff;
  text-align: center;
  z-index: 99;
  left: 0;
  top: 0;
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="direction_value">
</div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi ducimus expedita facilis architecto fugiat veniam natus suscipit amet beatae atque, enim recusandae quos, magnam, perferendis accusamus cumque nemo modi unde!</p>


1

当你在滚动元素时,在.data()中增加一个存储器,这样你就可以测试滚动次数是否到达了顶部。


1
为什么没有人在滚动时使用由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();
});

我正在使用 chromium,但我没有检查其他浏览器是否具有dir属性。

Chrome 86.0.4240.111 中没有“dir”属性。 - xtian

0

这是一种最佳解决方案,可以在用户结束滚动时检测方向。

var currentScrollTop = 0 ;

$(window).bind('scroll', function () {     

    scrollTop = $(this).scrollTop();

    clearTimeout($.data(this, 'scrollTimer'));
    $.data(this, 'scrollTimer', setTimeout(function() {

        if(scrollTop > currentScrollTop){
            // downscroll code
            $('.mfb-component--bl').addClass('mfbHide');
        }else{
            // upscroll code
            $('.mfb-component--bl').removeClass('mfbHide');
        }
        currentScrollTop = scrollTop;

    }, 250));

});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接