【问题标题】:Jquery .animate() stop scrolling when user scrolls manually?当用户手动滚动时,Jquery .animate() 停止滚动?
【发布时间】:2013-08-26 13:40:36
【问题描述】:

我已经设置了一个 sn-p,它可以在单击页面部分时将其滚动到视图中,问题是如果用户想要在动画中间滚动,滚动会有点卡顿。

    $( "section" ).click(function(e) {
        $('html,body').animate({ scrollTop: $(this).position().top }, 'slow');
        return false; 
    });

如果用户手动滚动,我如何停止 jquery 动画?

【问题讨论】:

    标签: javascript jquery css


    【解决方案1】:

    把你的函数改成这样:

    var page = $("html, body");
    
    $( "section" ).click(function(e) {
    
       page.on("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove", function(){
           page.stop();
       });
    
       page.animate({ scrollTop: $(this).position().top }, 'slow', function(){
           page.off("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove");
       });
    
       return false; 
    });
    

    这将:

    • 如果用户手动滚动则停止动画(仅在动画期间)
    • 不会妨碍您正常的 jQuery 动画,其他一些答案会

    一些额外的信息:

    为什么要绑定所有这些事件? “滚动鼠标滚轮等...”

    有许多不同类型的滚动事件。您可以使用鼠标、键盘、触摸屏等向下滚动。这样我们可以确保捕捉到所有。

    var page = $("html, body"); 有什么用?我不能到处使用$("html, body")吗?

    如果您多次使用同一个选择器,最好将它们缓存在variable 中。它会更容易编写/使用,并且比让程序每次都重新计算选择器具有更好的性能。

    在哪里可以找到有关.animate() 和.stop() 的更多信息?

    您可以阅读 .animate() 和 .stop() 的 jQuery 文档。我还建议阅读有关 animation queue's 的内容,因为 .stop() 就是按照这个原则工作的。

    【讨论】:

    【解决方案2】:

    我会通过检测用户事件来做到这一点

    $('body,html').bind('scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove', function (e) {
      if (e.which > 0 || e.type == "mousedown" || e.type == "mousewheel" || e.type == "touchmove") {
        $("html,body").stop();
      }
    });
    

    这里是a good tutorial。

    【讨论】:

      【解决方案3】:
      $("your selector").scroll(function(){
       $('html,body').stop();
      });
      

      参考stop

      【讨论】:

        【解决方案4】:

        试试这个

        $('html,body').scroll(function() {
            $(this).stop(true, false);
        });
        

        它还会从元素的队列中移除所有其他动画,但它不会“跳转”到当前滚动动画的末尾。

        【讨论】:

        • 我相信这会阻碍他原来的滚动动画。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多