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

时间:2010-12-01 16:57:59

标签: javascript jquery

我正在寻找这样的效果:

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

有什么想法吗?

25 个答案:

答案 0 :(得分:643)

检查当前scrollTop与之前的scrollTop

var lastScrollTop = 0;
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
       // downscroll code
   } else {
      // upscroll code
   }
   lastScrollTop = st;
});

答案 1 :(得分:162)

您可以执行此操作,而无需跟踪上一个滚动顶部,因为所有其他示例都需要:

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

我不是这方面的专家,所以请随意进一步研究,但看起来当你使用$(element).scroll时,正在收听的事件是'滚动'事件。

但是如果您使用bind专门侦听mousewheel事件,则回调的事件参数的originalEvent属性包含不同的信息。部分信息是wheelDelta。如果是正面,则向上移动鼠标滚轮。如果是负数,则向下移动鼠标滚轮。

我的猜测是,当鼠标滚轮转动时,mousewheel事件将会触发,即使页面不滚动;可能不会触发“滚动”事件的情况。如果需要,可以在回调的底部调用event.preventDefault()以防止页面滚动,这样您就可以将鼠标滚轮事件用于除页面滚动之外的其他内容,例如某种类型的缩放功能。 / p>

答案 2 :(得分:28)

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

这是一种避免任何全局变量(fiddle available here)的方法:

(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

答案 3 :(得分:28)

现有解决方案

此帖子中可能有 3解决方案other answer

解决方案1 ​​

    var lastScrollTop = 0;
    $(window).on('scroll', function() {
        st = $(this).scrollTop();
        if(st < lastScrollTop) {
            console.log('up 1');
        }
        else {
            console.log('down 1');
        }
        lastScrollTop = st;
    });

解决方案2

    $('body').on('DOMMouseScroll', function(e){
        if(e.originalEvent.detail < 0) {
            console.log('up 2');
        }
        else {
            console.log('down 2');
        }
    });

解决方案3

    $('body').on('mousewheel', function(e){
        if(e.originalEvent.wheelDelta > 0) {
            console.log('up 3');
        }
        else {
            console.log('down 3');
        }
    });

多浏览器测试

我无法在Safari

上测试它

chrome 42(Win 7)

  • 解决方案1
    • 向上:每1个卷轴1个事件
    • 向下:每1个滚动1个事件
  • Soltion 2
    • Up:不工作
    • 向下:不工作
  • 解决方案3
    • 向上:每1个卷轴1个事件
    • 向下:每1个滚动1个事件

Firefox 37(Win 7)

  • 解决方案1
    • 向上:每1卷滚动20个事件
    • 向下:每1卷滚动20个事件
  • Soltion 2
    • Up:不工作
    • 向下:每1个滚动1个事件
  • 解决方案3
    • Up:不工作
    • 向下:不工作

IE 11(Win 8)

  • 解决方案1
    • 向上:每1个滚动10个事件(副作用:最后发生向下滚动)
    • 向下:每1卷滚动10个事件
  • Soltion 2
    • Up:不工作
    • 向下:不工作
  • 解决方案3
    • Up:不工作
    • 向下:每1个滚动1个事件

IE 10(Win 7)

  • 解决方案1
    • 向上:每1个卷轴1个事件
    • 向下:每1个滚动1个事件
  • Soltion 2
    • Up:不工作
    • 向下:不工作
  • 解决方案3
    • 向上:每1个卷轴1个事件
    • 向下:每1个滚动1个事件

IE 9(Win 7)

  • 解决方案1
    • 向上:每1个卷轴1个事件
    • 向下:每1个滚动1个事件
  • Soltion 2
    • Up:不工作
    • 向下:不工作
  • 解决方案3
    • 向上:每1个卷轴1个事件
    • 向下:每1个滚动1个事件

IE 8(Win 7)

  • 解决方案1
    • 向上:每1个卷轴发生2个事件(副作用:最后发生向下滚动)
    • 向下:每1卷滚动2~4个事件
  • Soltion 2
    • Up:不工作
    • 向下:不工作
  • 解决方案3
    • 向上:每1个卷轴1个事件
    • 向下:每1个滚动1个事件

组合解决方案

  

我检查了IE 11和IE 8的副作用来自if else声明。因此,我将其替换为if else if语句,如下所示。

在多浏览器测试中,我决定对常见浏览器使用 Solution 3 ,对firefox和IE 11使用 Solution 1

我提到this answer来检测IE 11。

    // Detect IE version
    var iev=0;
    var ieold = (/MSIE (\d+\.\d+);/.test(navigator.userAgent));
    var trident = !!navigator.userAgent.match(/Trident\/7.0/);
    var rv=navigator.userAgent.indexOf("rv:11.0");

    if (ieold) iev=new Number(RegExp.$1);
    if (navigator.appVersion.indexOf("MSIE 10") != -1) iev=10;
    if (trident&&rv!=-1) iev=11;

    // Firefox or IE 11
    if(typeof InstallTrigger !== 'undefined' || iev == 11) {
        var lastScrollTop = 0;
        $(window).on('scroll', function() {
            st = $(this).scrollTop();
            if(st < lastScrollTop) {
                console.log('Up');
            }
            else if(st > lastScrollTop) {
                console.log('Down');
            }
            lastScrollTop = st;
        });
    }
    // Other browsers
    else {
        $('body').on('mousewheel', function(e){
            if(e.originalEvent.wheelDelta > 0) {
                console.log('Up');
            }
            else if(e.originalEvent.wheelDelta < 0) {
                console.log('Down');
            }
        });
    }

答案 4 :(得分:12)

我知道已经有一个已接受的答案,但想发布我正在使用的内容,以防它可以帮助任何人。我通过鼠标滚轮事件获得cliphex的方向,但支持Firefox。如果您正在执行锁定滚动操作并且无法获取当前滚动顶部的话,这样做很有用。

查看实时版本here

$(window).on('mousewheel DOMMouseScroll', function (e) {

    var direction = (function () {

        var delta = (e.type === 'DOMMouseScroll' ?
                     e.originalEvent.detail * -40 :
                     e.originalEvent.wheelDelta);

        return delta > 0 ? 0 : 1;
    }());

    if(direction === 1) {
       // scroll down
    }
    if(direction === 0) {
       // scroll up
    }
});

答案 5 :(得分:8)

滚动事件

scroll event 在FF中表现得很奇怪(由于平滑滚动,它很多次被触发)但是它有效。

注意:使用光标键或鼠标滚轮拖动滚动条时,scroll事件实际被触发

//creates an element to print the scroll position
$("<p id='test'>").appendTo("body").css({
    padding: "5px 7px",
    background: "#e9e9e9",
    position: "fixed",
    bottom: "15px",
    left: "35px"
});

//binds the "scroll" event
$(window).scroll(function (e) {
    var target = e.currentTarget,
        self = $(target),
        scrollTop = window.pageYOffset || target.scrollTop,
        lastScrollTop = self.data("lastScrollTop") || 0,
        scrollHeight = target.scrollHeight || document.body.scrollHeight,
        scrollText = "";

    if (scrollTop > lastScrollTop) {
        scrollText = "<b>scroll down</b>";
    } else {
        scrollText = "<b>scroll up</b>";
    }

    $("#test").html(scrollText +
      "<br>innerHeight: " + self.innerHeight() +
      "<br>scrollHeight: " + scrollHeight +
      "<br>scrollTop: " + scrollTop +
      "<br>lastScrollTop: " + lastScrollTop);

    if (scrollHeight - scrollTop === self.innerHeight()) {
      console.log("► End of scroll");
    }

    //saves the current scrollTop
    self.data("lastScrollTop", scrollTop);
});

轮子事件

您还可以查看MDN,它会显示有关 Wheel Event的详细信息。

注意:仅在使用鼠标滚轮时才会触发滚轮事件 ;光标键并拖动滚动条不会触发事件。

我阅读了文档和示例: Listening to this event across browser
经过FF,IE,Chrome,safari的一些测试后,我最终得到了这个片段:

//creates an element to print the scroll position
$("<p id='test'>").appendTo("body").css({
    padding: "5px 7px",
    background: "#e9e9e9",
    position: "fixed",
    bottom: "15px",
    left: "15px"
});

//attach the "wheel" event if it is supported, otherwise "mousewheel" event is used
$("html").on(("onwheel" in document.createElement("div") ? "wheel" : "mousewheel"), function (e) {
    var evt = e.originalEvent || e;

    //this is what really matters
    var deltaY = evt.deltaY || (-1 / 40 * evt.wheelDelta), //wheel || mousewheel
        scrollTop = $(this).scrollTop() || $("body").scrollTop(), //fix safari
        scrollText = "";

    if (deltaY > 0) {
        scrollText = "<b>scroll down</b>";
    } else {
        scrollText = "<b>scroll up</b>";
    }

    //console.log("Event: ", evt);
    $("#test").html(scrollText +
      "<br>clientHeight: " + this.clientHeight +
      "<br>scrollHeight: " + this.scrollHeight +
      "<br>scrollTop: " + scrollTop +
      "<br>deltaY: " + deltaY);
});

答案 6 :(得分:8)

如果您只是想知道使用指针设备(鼠标或触控板)向上或向下滚动,可以使用wheel事件的deltaY属性。

&#13;
&#13;
$('.container').on('wheel', function(event) {
  if (event.originalEvent.deltaY > 0) {
    $('.result').append('Scrolled down!<br>');
  } else {
    $('.result').append('Scrolled up!<br>');
  }
});
&#13;
.container {
  height: 200px;
  width: 400px;
  margin: 20px;
  border: 1px solid black;
  overflow-y: auto;
}
.content {
  height: 300px;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 7 :(得分:3)

var tempScrollTop, currentScrollTop = 0; 

$(window).scroll(function(){ 

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

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

  tempScrollTop = currentScrollTop; 
} 

或使用mousewheel extension,请参阅here

答案 8 :(得分:3)

我在这里看到很多版本的好答案,但似乎有些人有跨浏览器问题,所以这是我的修复。

我已经成功地使用它来检测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();

答案 9 :(得分:3)

要忽略页面顶部和底部的任何快照/动量/反弹,这里是Josiah's accepted answer的修改版本:

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

答案 10 :(得分: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');
    }
});

答案 11 :(得分:2)

此代码可与IE,Firefox,Opera和Chrome配合使用:

>>> df1
   A    B    C    D
0 -0.8 -2.8 -0.3 -0.1
1 -0.1 -0.9  0.2 -0.7
2  0.7 -3.3 -1.1 -0.4 

>>> df2
   A    B    C    D
0  1.4 -0.7  1.5 -1.3
1  1.6  1.4  1.4  0.2
2 -1.4  0.2 -1.7  0.7 

>>> df3
   A    B    C    D
0  0.3 -0.5 -1.6 -0.8
1  0.2 -0.5 -1.1  1.6
2 -0.3  0.7 -1.0  1.0

“滚轮鼠标滚轮” 和属性 deltaY 必须在 bind()函数中使用。

记住:出于安全原因,您是用户,必须更新其系统和浏览器。在2018年,“我有IE 7”的借口是胡说八道。我们必须教育用户。

祝你有美好的一天:)

答案 12 :(得分:2)

使用此选项查找滚动方向。这只是为了找到垂直滚动的方向。支持所有跨浏览器。

    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

答案 13 :(得分:2)

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

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

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

你也可以用(窗口)替换'body'。

答案 14 :(得分:2)

保持简单:

jQuery事件监听器方式:

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

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

我在帖子上写了一篇更深入的帖子here

答案 15 :(得分:1)

自从v3上的bind has been deprecated(“被on取代”)和wheel is now supported以来,忘记了wheelDelta

$(window).on('wheel', function(e) {
  if (e.originalEvent.deltaY > 0) {
    console.log('down');
  } else {
    console.log('up');
  }
  if (e.originalEvent.deltaX > 0) {
    console.log('right');
  } else {
    console.log('left');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 style="white-space:nowrap;overflow:scroll">
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
</h1>

wheel事件的Browser Compatibility on MDN's (2019-03-18)

Compatibility of the wheel event

答案 16 :(得分:1)

为什么没人在滚动时使用event返回的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属性。

答案 17 :(得分:1)

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

答案 18 :(得分:0)

我遇到了问题,并且出现了弹性滚动(滚动弹跳,橡皮筋)。 如果靠近页面顶部对我有用,则忽略向下滚动事件。

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

答案 19 :(得分:0)

您也可以使用它

$(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>

答案 20 :(得分:0)

这适用于所有PC或手机浏览器,并扩展了最前面的答案。可以构建一个更复杂的事件对象window [“ scroll_evt”],然后在handleScroll()函数中对其进行调用。如果经过一定的延迟或传递了一定的增量以消除某些不必要的触发,则此触发将触发2个并发条件。

window["scroll_evt"]={"delta":0,"delay":0,"direction":0,"time":Date.now(),"pos":$(window).scrollTop(),"min_delta":120,"min_delay":10};
$(window).scroll(function() {

    var currentScroll = $(this).scrollTop();
    var currentTime = Date.now();
    var boolRun=(window["scroll_evt"]["min_delay"]>0)?(Math.abs(currentTime - window["scroll_evt"]["time"])>window["scroll_evt"]["min_delay"]):false;
    boolRun = boolRun && ((window["scroll_evt"]["min_delta"]>0)?(Math.abs(currentScroll - window["scroll_evt"]["pos"])>window["scroll_evt"]["min_delta"]):false);
    if(boolRun){
        window["scroll_evt"]["delta"] = currentScroll - window["scroll_evt"]["pos"];
        window["scroll_evt"]["direction"] = window["scroll_evt"]["delta"]>0?'down':'up';
        window["scroll_evt"]["delay"] =currentTime - window["scroll_evt"]["time"];//in milisecs!!!
        window["scroll_evt"]["pos"] = currentScroll;
        window["scroll_evt"]["time"] = currentTime;
        handleScroll();
    }
});


function handleScroll(){
    event.stopPropagation();
    //alert(window["scroll_evt"]["direction"]);
    console.log(window["scroll_evt"]);
}

答案 21 :(得分:0)

你应该试试这个

var scrl
$(window).scroll(function(){
        if($(window).scrollTop() < scrl){
            //some code while previous scroll
        }else{
            if($(window).scrollTop() > 200){
                //scroll while downward
            }else{//scroll while downward after some specific height
            }
        }
        scrl = $(window).scrollTop();
    });

答案 22 :(得分: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));

});

答案 23 :(得分:0)

当用户滚动离开页面顶部时以及当它们返回顶部时,这是简单易行的检测。

$(window).scroll(function() {
    if($(window).scrollTop() > 0) {
        // User has scrolled
    } else {
        // User at top of page
    }
});

答案 24 :(得分:0)

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

{ top : 1,
   first_top_event: function(){ ...},
   second_top_event: function(){ ...},
   third_top_event: function(){ ...},
   scroll_down_event1: function(){ ...},
   scroll_down_event2: function(){ ...}
}
相关问题