检测用户向下滚动或向上滚动jQuery

时间:2012-03-31 16:56:51

标签: jquery events scroll bind

  

可能重复:
  Differentiate between scroll up/down in jquery?

是否可以检测用户是向下滚动还是向上滚动?

示例:

$(window).scroll(function(){

    // IF USER SCROLL DOWN 
           DO ACTION

    // IF USER SCROLL UP 
           DO ANOTHER ACTION

});

由于

1 个答案:

答案 0 :(得分:47)

要区分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
    }   
});

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

的div

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