jQuery stop(true, true) to jump to end of all animations in queue

不羁的心 提交于 2019-12-09 09:18:37

问题


I have been using jQuery's stop(true, true) method to clear running animations so the next one starts immediately. I noticed that the first parameter, clearQueue, clears the entire animation queue but the second parameter, jumpToEnd, only jumps to the end of the currently running animation and not the ones that were removed from the queue. Is there a way to have it clear and jump to the end of all queued animations?

I've ended up chaining a few stop(false, true) calls instead, but this will only handle 3 queued animations, for example.

$(this)
  .stop(false, true)
  .stop(false, true)
  .stop(false, true)
  .addClass('hover', 200);

Edit:

I ended up adding my own method, stopAll, as per Ates Goral's answer:

$.fn.extend({ stopAll: function () {
    while (this.queue().length > 0)
      this.stop(false, true);
    return this;
  } });
$(this).stopAll().addClass('hover', 200);

I hope someone else finds this useful.


回答1:


jQuery 1.9 introduced the .finish() method, which achieves exactly that.




回答2:


Chaining multiple stop(false, true) makes sense. Instead of hard-coding a fixed number of chained calls, you could check the queue length:

while ($(this).queue().length) {
    $(this).stop(false, true);
}

Demo: http://jsfiddle.net/AB33X/




回答3:


I also notice from the documentation of the .finish() method in jQuery 1.9 that

Animations may be stopped globally by setting the property $.fx.off 
to true. When this is done, all animation methods will immediately 
set elements to their final state when called, rather than displaying an effect.

There is also a nice demo of the various methods on the .finish() documentation page.




回答4:


Test for presence of class (set upon hover and removed on mouseOut animate callback) before staring new animation. When new animation does start, dequeue.

$("div").hover(function(){
    if (!$(this).hasClass('animated')) {
        $(this).dequeue().stop().animate({ width: "200px" });
    }
}, function() {
    $(this).addClass('animated').animate({ width: "100px" }, "normal", "linear", function() {
        $(this).removeClass('animated').dequeue();
    });
});


来源:https://stackoverflow.com/questions/9747576/jquery-stoptrue-true-to-jump-to-end-of-all-animations-in-queue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!