2017-01-12 29 views
0

我有一个简单的JS,它可以顺利地自动滚动到另一个div,只要鼠标滚轮向上或向下移动。JavaScript/JQuery - 如何在使用后暂时禁用功能?

这里的脚本:

$(document).bind('mousewheel', function(evt) { 
     var delta = evt.originalEvent.wheelDelta 
     if(delta < 0){ 
       $('html, body').animate({ 
        scrollTop: $("#content-wrapper").offset().top 
       }, 3000); 
     } 
     else { 
       $('html, body').animate({ 
       scrollTop: $("#bgheader").offset().top 
       }, 3000); 
     }   
    }); 

我的问题是,如果我用鼠标滚轮几秒钟发挥将开始在这里和那里永远滚动,因为每个记录的举动排队为其他脚本启动。

有什么方法可以对脚本进行某种“冷却”吗?所以,使用一次后,它会变得可用再次使用,让我们说'3秒?或者一旦动画完成?

+3

谷歌“反跳”。 – Barmar

+0

可能相关:[如何禁用滚动临时](http://stackoverflow.com/questions/4770025/how-to-disable-scrolling-temporarily) – Hodrobond

+0

Barmar-我听说过它,但作为我的知识jQuery /纯js是有点限制我试图远离UnderScore和其他图书馆,仍然debounceing肯定会解决这个问题,所以感谢贡献! –

回答

1

您可以取消绑定滚轮事件侦听器,然后使用jQuery的.animate()回调函数来重新附加事件监听器它完成后,像这样:

function scrollHandler (event) { 
    $(document).off("mousewheel.custom"); 
    var delta = event.originalEvent.wheelDelta 
    if(delta < 0){ 
     $('html, body').animate({ 
      scrollTop: $("#content-wrapper").offset().top 
     }, 3000, function() { 
      // animation callback function 
      $(document).on("mousewheel.custom", scrollHandler); 
     })); 
    } 
    else { 
     $('html, body').animate({ 
      scrollTop: $("#bgheader").offset().top 
     }, 3000, function() { 
      // animation callback function 
      $(document).on("mousewheel.custom", scrollHandler); 
     }); 
    } 
} 

// namespace the event so we can easily .off() it 
$(document).on('mousewheel.custom', scrollHandler); 
+0

这是完美的,可能是最好的方式来解决它,而不使用像UnderScore.js这样的外部库,它具有去抖功能。谢谢mhodges! –

+0

@DamianDoman不客气!很高兴它对你有效! =) – mhodges

0

我使用了超时。

var maxPoll = 3000, 
    eventActive = false; 

$(document).bind('mousewheel', function(evt) { 
    if(eventActive) { 
     return 
    } else { 
     setTimeout(maxPoll, function() { eventActive = True }) 
    } 
    var delta = evt.originalEvent.wheelDelta 
    if(delta < 0){ 
     $('html, body').animate({ 
      scrollTop: $("#content-wrapper").offset().top 
     }, maxPoll); 
    } 
    else { 
     $('html, body').animate({ 
      scrollTop: $("#bgheader").offset().top 
     }, maxPoll); 
    }   
}); 

这很粗糙,它使用全局变量,但它基本上关闭您的事件,而动画正在运行。

+0

是的,我已经尝试使用超时,但它仍然启动大量的脚本运行,他们只是延迟了3秒。感谢您的回复寿! –