【问题标题】:How to cancel a javascript function if the user scrolls the page如果用户滚动页面,如何取消javascript函数
【发布时间】:2017-11-16 18:21:19
【问题描述】:

使用此 javascript 在使用 setTimeout 延迟 5 秒后滚动到 div (#Content)。

setTimeout(function () {
    $('html, body').animate({ scrollTop: $('#Content').offset().top - 0 }, 1000);
}, 5000);

如果用户在 5 秒过去之前手动滚动,我将如何取消此操作。原因是如果用户滚动了页面,他们会因为页面自动滚动而烦恼。

尝试将其放入 window.load 并检查 if ($(window).scrollTop() == 0) 但当然在 window.load 中总是如此,并且不会被用户手动滚动取消。

谢谢!

【问题讨论】:

    标签: javascript scroll


    【解决方案1】:

    您可以通过为scroll 添加事件处理程序来运行检查滚动的逻辑,然后在完成检查后删除事件处理程序,因为它只需要运行一次。另外,您可以使用 eventHandler 代码中的 clearTimeout 清除 setTimeout。

    window.addEventListener('scroll', scrollEventHandler);
    
    function scrollEventHandler(e){
        clearTimeout(...setTimeoutid) // Pass in setTimeout Id.    
    }
    
    setTimeout(function () {
             $('html, body').animate({ scrollTop: $('#Content').offset().top - 0 }, 1000);
             window.removeEventListener('scroll', scrollEventHandler);
    }, 5000);
    

    【讨论】:

      【解决方案2】:

      您可以像其他人显示的那样清除超时,或者您可以让它运行但在开始滚动动画之前执行里面的 scrollTop 检查:

      setTimeout(function () {
          if ($(window).scrollTop() == 0) {
              $('html, body').animate({ scrollTop: $('#Content').offset().top - 0 }, 1000);
          }
      }, 5000);
      

      【讨论】:

        【解决方案3】:

        您应该将超时定义为一个变量,以便能够使用 clearTimeout 取消它

        在此处查看完整文档:https://www.w3schools.com/jsref/met_win_cleartimeout.asp

        只需添加一个事件来检查您的滚动并在滚动时清除您的超时

        例如:

        var myVar = setTimeout(function(){ 
           $('html, body').animate({ scrollTop: $('#Content').offset().top - 0 }, 1000); 
        }, 5000);
        

        并取消您的滚动:

        $(document).scroll(function(){
         clearTimeout(myVar)
        }
        

        【讨论】:

          【解决方案4】:

          您可以使用例如全局变量并检查它是否由事件滚动设置

          var scrolled = false;
          $(document).scroll(function(){scrolled = true;});
          setTimeout(function () { 
           if (!scrolled){
              $('html, body').animate({ scrollTop: $('#Content').offset().top - 0 }, 
              1000); }
            }
          }, 5000);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-06-12
            • 2011-05-04
            • 2017-04-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多