jQuery 区分jquery中向上/向下滚动?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4989632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:20:13  来源:igfitidea点击:

Differentiate between scroll up/down in jquery?

jqueryscroll

提问by Hanna

I have found some great ways to check for where the scroll bar is using jquery, but I was wondering if you can differentiate whether or not the user scrolled up or down?

我找到了一些很好的方法来检查滚动条使用 jquery 的位置,但我想知道您是否可以区分用户是向上还是向下滚动?

采纳答案by Gabi Purcaru

Check for the last state. Something like this:

检查最后一个状态。像这样的东西:

Keep a variable, say, last_scroll_position, and when you have a scroll, if last_scroll_position - current_position > 0, the user scrolled up, and down if it's less than 0.

保持一个变量,比如说,last_scroll_position,当你有一个滚动时,如果last_scroll_position - current_position > 0,用户向上滚动,如果它小于 0,则向下滚动。

回答by Iman Sedighi

<script type='text/javascript'>
$(function(){

  var CurrentScroll = 0;
  $(window).scroll(function(event){

      var NextScroll = $(this).scrollTop();

      if (NextScroll > CurrentScroll){
         //write the codes related to down-ward scrolling here
      }
      else {
         //write the codes related to upward-scrolling here
      }

      CurrentScroll = NextScroll;  //Updates current scroll position
  });
});

回答by Jordi van Duijn

To differentiate between scroll up/down in jQuery, you could use:

要区分 jQuery 中的向上/向下滚动,您可以使用:

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){

    var evt = window.event || e //equalize event object     
    evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
    var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF

    if(delta > 0) {
        //scroll up
    }
    else{
        //scroll down
    }   
});

This method also works in divs that have overflow:hidden.

此方法也适用于具有overflow:hidden.

I successfully tested it in FireFox, IE and Chrome.

我在 FireFox、IE 和 Chrome 中成功测试了它。

回答by jherax

Scroll Event

滚动事件

The scroll eventbehaves oddly in FF (it is fired a lot of times because of the smoothness scrolling) but it works.

滚动事件会出现很奇怪的FF(它开了很多次,因为平滑滚动),但它的工作原理。

Note:The scrollevent actually is firedwhen dragging the scroll bar, using cursor keys or mousewheel.

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

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


Wheel Event

车轮事件

You also may take a look at MDN, it exposes a great information about the Wheel Event.

您也可以查看 MDN,它公开了有关Wheel Event的大量信息

Note:The wheel event is fired only when using the mousewheel; cursor keys and dragging the scroll bar does not fire the event.

注意:wheel 事件只有在使用 mousewheel 时才会触发;光标键和拖动滚动条不会触发该事件。

I read the document and the example: Listening to this event across browser
and after some tests with FF, IE, chrome, safari, I ended up with this snippet:

我阅读了文档和示例:在浏览器中收听此事件,
并在使用 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);
});

回答by Henrik Christensen

Example for vanilla javascript:

香草 javascript 示例:

var f = (function(){
    var oldPos = window.scrollY;
    function fu(e) {
        var newPos = window.scrollY;
        if (newPos>oldPos) {
            console.log('down');
        } else if(newPos<oldPos) {
            console.log('up');
        } else {
            console.log('same');
        }
        oldPos = newPos;
    }
    return fu;
})();
window.addEventListener('scroll',f);

回答by monday

There is a simple way to do it without global variables of any kind. MouseWheel event has a property explicitly specifying scrolling direction. Here's how to use it:

有一种简单的方法可以在没有任何类型的全局变量的情况下做到这一点。MouseWheel 事件具有明确指定滚动方向的属性。以下是如何使用它:

   $("#scroll_div").bind("mousewheel",function(ev) {
      var curScrollLeft = $(this).scrollLeft();
      $(this).scrollLeft(curScrollLeft + Math.round(ev.originalEvent.wheelDelta));
    });