How can I determine the direction of a jQuery scroll event?

后端 未结 25 1455
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 22:24

I\'m looking for something to this effect:

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


        
25条回答
  •  你的背包
    2020-11-21 23:13

    This works in all pc or phones browsers, expanding on the top answers. One can build a more complex event object window["scroll_evt"] then call it in the handleScroll() function. This one triggers for 2 concurrent conditions, if certain delay has elapsed or certain delta is passed to eliminate some unwanted triggers.

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

提交回复
热议问题