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

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

    I understand there has already been an accepted answer, but wanted to post what I am using in case it can help anyone. I get the direction like cliphex with the mousewheel event but with support for Firefox. It's useful doing it this way in case you are doing something like locking scroll and can't get the current scroll top.

    See a live version here.

    $(window).on('mousewheel DOMMouseScroll', function (e) {
    
        var direction = (function () {
    
            var delta = (e.type === 'DOMMouseScroll' ?
                         e.originalEvent.detail * -40 :
                         e.originalEvent.wheelDelta);
    
            return delta > 0 ? 0 : 1;
        }());
    
        if(direction === 1) {
           // scroll down
        }
        if(direction === 0) {
           // scroll up
        }
    });
    

提交回复
热议问题