2016-05-25 166 views
0

當兩個向上和向下我有向上滾動時,向下滾動時應該控制檯登錄updown功能。向上滾動觸發滾動起來

向下滾動工作正常,但向上滾動控制檯時記錄了updown

爲什麼滾動向上只是在記錄up,因爲它只是在向下滾動時記錄down

function scrollTest() { 

     var lastScrollTop = 0; 

     $(window).scroll(function(event) { 

      var st = $(this).scrollTop(); 

      if (st > lastScrollTop){ 
       console.log('down'); 
      } else if (st < lastScrollTop) { 
       console.log('up'); 
      } 

      lastScrollTop = st; 

     }); 

    }; 

$(window).on("scroll", function() { 

    scrollTest(); 

}); 

回答

1

更改爲

function scrollTest(){ 
      var lastScrollTop = $(window).scrollTop(); 
      $(window).scroll(function(event) { 

      var st = $(this).scrollTop(); 

      if (st > lastScrollTop){ 
       console.log('down'); 
      } else if (st < lastScrollTop) { 
       console.log('up'); 
      } 

      lastScrollTop = st; 

     }); 
      }   
    $(window).on("scroll", function() { 
      scrollTest(); 
    }); 

var lastScrollTop = 0正在創建該問題。 意味着沒有冒犯對方的回答或它的作者,我覺得 它通常是一個壞主意,有一個全局變量。

1

此修復:

var lastScrollTop = 0; 
function scrollTest() { 


    $(window).scroll(function(event) { 

     var st = $(this).scrollTop(); 

     if (st > lastScrollTop){ 
      console.log('down ' + st + " | " + lastScrollTop); 
      lastScrollTop = st; 
      return 0; 
     } 
     if (st < lastScrollTop) { 
      console.log('up ' + st + " | " + lastScrollTop); 
      lastScrollTop = st; 
      return 0; 
     } 
     }); 

    }; 

$(window).on("scroll", function() { 

    scrollTest(); 

}); 

的問題是,var lastScrollTop = 0;是在代碼中獲取值0每個滾動... here is the fiddle