2017-05-07 49 views
0

我使用wheelDelta檢查滾動方向,但它一次返回大量的滾動屬性。我只需要知道它是否已啓動或關閉,並且在第一次觸發後它不應該在500毫秒內返回一個值。我試圖玩setTimeout,但不能很好地解決它。有任何想法嗎?jQuery功能 - 阻止獲得回報「一段時間」

var distance = $('.section-two').offset().top, 
    $window = $(window); 

    $window.scroll(function() { 
     if ($window.scrollTop() >= distance) { 
      $('body').css('overflow', 'hidden'); 
      setTimeout(function(){ 
       $(document).bind('mousewheel', function(evt) { 

        var delta = evt.originalEvent.wheelDelta; 
        if(delta > 0){ 

         console.log('scrolled up') 
        } else { 
         console.log('scrolled down'); 
        } 
       }) 
      }, 500); 
     } 
    }); 

enter image description here 這裏的codepen example

回答

1

能您嘗試之前解除綁定'mousewheel'事件綁定。它似乎是,它一遍又一遍地綁定它。在$(document).bind('mousewheel', function(evt) {行之前添加$(document).unbind('mousewheel');

+0

感謝烏米特,它實際上有點幫助,但無法解決問題。我還將示例上傳到了CodePen:https://codepen.io/cangoktas/pen/wdPYEy –

+0

隨着解除綁定,它將在鼠標滾輪的每個勾號中返回1個結果。這是聽衆'鼠標滾輪'可以獲得的最低結果。如果你想讓它工作的話;在拖動鼠標滾輪而不重置它的情況下,它只返回一個結果,您應該考慮更改事件偵聽器。編輯CodePen:https://codepen.io/anon/pen/vmWVVg –

+0

我想我有點整理出來setTimeout:https://codepen.io/cangoktas/pen/LyOgqN再次感謝,iyi geceler :) –

0

嘗試使用Lodash來限制事件。你應該能夠存儲先前偏移,並計算出從滾動方向:

var lastScrollTop = 0; 
 

 
function scrollHandler() { 
 
    var scrollTop = window.pageYOffset || document.documentElement.scrollTop; 
 

 
    if (scrollTop > lastScrollTop){ 
 
     console.info('scrolled down'); 
 
    } else { 
 
     console.info('scrolled up'); 
 
    } 
 
    
 
    lastScrollTop = scrollTop; 
 
} 
 

 
window.addEventListener('scroll', _.throttle(scrollHandler, 500))
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

+0

謝謝,試過Lodash但我禁用滾動溢出:隱藏;然後嘗試檢測滾動檢測,所以Lodash無法檢測到它。 –

+1

在這種情況下,請參閱http://stackoverflow.com/questions/8378243/catch-scrolling-event-on-overflowhidden-element。 – Conan

0

一個更合適的setTimeout解決:codepen example

var doMouseWheel = true; 
       $(document).bind("mousewheel", function(event, delta) 
       { 
         // it'll just not do anything while it's false 
         if (!doMouseWheel) 
          return; 

         // here's where you were unbinding, now just turning false 
         doMouseWheel = false; 

         // do whatever else you wanted 
         var delta = event.originalEvent.wheelDelta; 
         if(delta > 0){ 
          console.log('scrolled up') 
         } else { 
          console.log('scrolled down'); 
         } 

         // here's where you were rebinding, now wait 200ms and turn on 
         setTimeout(turnWheelBackOn, 800); 
       }); 

       function turnWheelBackOn() { doMouseWheel = true; }