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

Han*_*nna 17 jquery scroll

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

Gab*_*aru 18

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

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

  • 只是好奇,为什么不只是......`last_scroll_position <current_position //向下滚动`反之亦然?是否有理由减去然后比较而不仅仅是比较? (4认同)

Ima*_*ghi 14

<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
  });
});
Run Code Online (Sandbox Code Playgroud)


Jor*_*ijn 9

要区分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
    }   
});
Run Code Online (Sandbox Code Playgroud)

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

我在FireFox,IE和Chrome中成功测试了它.