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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9957860/
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-27 11:30:16  来源:igfitidea点击:

Detect user scroll down or scroll up in jQuery

jqueryeventsscrollbind

提问by Steffi

Possible Duplicate:
Differentiate between scroll up/down in jquery?

可能的重复:
区分在 jquery 中向上/向下滚动?

Is it possible to detect if user scroll down or scroll up ?

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

Example :

例子 :

$(window).scroll(function(){

    // IF USER SCROLL DOWN 
           DO ACTION

    // IF USER SCROLL UP 
           DO ANOTHER ACTION

});

Thanks

谢谢

回答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 中成功测试了它。