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

后端 未结 25 1487
爱一瞬间的悲伤
爱一瞬间的悲伤 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:10

    I have seen many version of good answers here but it seems some folks are having cross browser issues so this is my fix.

    I have used this successfully to detect direction in FF, IE and Chrome ... I haven't tested it in safari as I use windows typically.

    $("html, body").bind({'mousewheel DOMMouseScroll onmousewheel touchmove scroll': 
        function(e) {
            if (e.target.id == 'el') return;
            e.preventDefault();
            e.stopPropagation();
    
            //Determine Direction
            if (e.originalEvent.wheelDelta && e.originalEvent.wheelDelta >= 0) {
                //Up
                alert("up");
    
            } else if (e.originalEvent.detail && e.originalEvent.detail <= 0) {
                //Up
                alert("up");
    
            } else {
                //Down
                alert("down");
            }
        }
    });
    

    Keep in mind I also use this to stop any scrolling so if you want scrolling to still occur you must remove the e.preventDefault(); e.stopPropagation();

提交回复
热议问题