防止对某些事件进行进一步的动画处理

preventing from animating further on some event

本文关键字:进一步 动画 处理 事件      更新时间:2023-09-26

我这里有这段代码:

$(document).ready(function()
{
    $("#nav_items > p:first-child").click(function()
    {
        $('html,body').animate(
        {
            scrollTop: $('#main_div').offset().top
        }, 500);
    });
    $("#nav_items > p:last-child").click(function()
    {
        $('html,body').animate(
        {
            scrollTop: $('#about_us').offset().top
        }, 800);
    });
});

在元素 (p) 上,单击它将文档滚动到 #main_div 或 #about_us 元素。例如,如果我开始使用鼠标滚轮滚动,如何阻止它继续滚动?

您可以侦听 mousewheel 事件并使用 stop 方法:

$(window).on('mousewheel', function() {
   $('body, html').stop();
});

这是一个方法,结合了 $(window).scroll()$('body').on('mousewheel') 的使用,它将演示如何做你想要的事情:

jsFiddle 演示

var scrollPause = 0;
menuItems.click(function(e){
   var href = $(this).attr("href"),
      offsetTop = href === "#" ? 0 : $(href).offset().top-topMenuHeight+1;
   scrollPause = 1;
   $('html, body').stop().animate({ 
      scrollTop: offsetTop
   }, 300, function(){
       setTimeout(function(){
           scrollPause = 0;
       },5000);
   });
  e.preventDefault();
});
$('body').on({
    'mousewheel': function(e) {
        if (scrollPause == 0) return;
        e.preventDefault();
        e.stopPropagation();
    }
})

笔记:

  1. 在 jsFiddle 中,spdiv 用于直观地显示 scrollPause 变量的状态

  2. 单击顶部菜单项后,滚动暂停设置为0(禁止滚动),并使用setTimeout在暂停 8 秒后重新启用它。因此,在滚动到元素之后,鼠标滚轮滚动将立即禁用 8 秒。