美文网首页
使用 stop() 或 clearQueue() 阻止 jQu

使用 stop() 或 clearQueue() 阻止 jQu

作者: 老码农不上班 | 来源:发表于2016-09-14 11:17 被阅读421次

    使用 jQuery animation 动画的场景比较常见。譬如鼠标 hover 事件,使用 jQuery animation 进行样式修改;或者 click 事件,使用 jQuery animation 把某个元素滑动到指定位置 .animate({ scrollTop: $(window).height()}, 800);
    当 jQuery animation 函数一执行,动画在中途不会结束。假如在第一种场景下,如果我反复地把光标 hover 在绑定了 animation 动画的元素上,就会形成一个队列,前一次 hover 不会因为后一次的 hover 而停止 animation ; 而第二种场景,当用户点击按钮之后,页面开始滚动了,但是当用户试图使用鼠标滑轮阻止页面滚动时,此时动画滚动是不会停止的。这些效果不是我们想要的,但是使用 stop()或者 clearQueue函数能够让 animation 停止。

    • 场景一

      $(".stop li").hover(
        function () {
            $(this).stop().animate({width:"100px"},500);
        },
         function () {
          $(this).stop().animate({width:"80px"},500);
        }
      );
      

      stop() 绑定在指定元素中,当前运行中的动画就会被组织,继而进行下个动画。而不是等待第一个动画执行结束再接着执行第二个动画。

    • 场景二

      //点击事件触发滑动
      $("body").animate({ scrollTop: $(window).height()}, 800);
      ...
      //鼠标滑轮或者鼠标按键组织滑动事件
      $('html,body').on("scroll mousedown DOMMouseScroll mousewheel keyup", function(e){
        if ( e.which > 0 || e.type === "mousedown" || e.type === "mousewheel"){
          $('html,body').stop().on('scroll mousedown DOMMouseScroll mousewheel keyup');
        }
      });
      

    stop()函数仅仅在 animations 中起作用,如果我们想组织其它函数的队列,我们可以使用 clearQueue()函数。
    Demo

    相关文章

      网友评论

          本文标题:使用 stop() 或 clearQueue() 阻止 jQu

          本文链接:https://www.haomeiwen.com/subject/kpsvettx.html