Stopping specific jQuery animations

前端 未结 5 676
一整个雨季
一整个雨季 2020-12-10 05:33

I have multiple animations on a single object, and I need to stop a specific animation rather than all of them. It doesn\'t look like the .stop() method can do this.

<
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-10 06:06

    I hate to be a guy who answers his own question (thanks so much for the detailed responses and putting brain power into it!) but I have found a direct answer. Apparently there is a parameter for the .animate() method called "queue" which defaults to true but you can set to false in order to have your animation take place immediately.

    This means that by setting queue to false you can run multiple animations using separate calls without having to wait for the previous one to finish. Better yet, if you try to run an animation for a property which is already being animated, the second will override the first. This means you can stop a property's animation by simply "animating" it to its current value with a duration of 0, using queue "false".

    An Example:

    $myElement = $("#animateElement");
    $myElement.animate({width: 500}, {duration: 5000});
    $myElement.animate({height: 500}, {duration: 5000, queue: false});
    // ... Wait 2 seconds ...
    $myElement.animate({width: $myElement.width()}, {duration: 0, queue: false});
    

    Another option was suggested by a gracious jQuery contributor who responded to my enhancement request. This takes advantage of the ability to use a step function on an animation (step functions are called at every point in the animation, and you can manipulate the animation parameters based on whatever criteria you want). Although this also could have solved the issue, I felt it was far more dirty than the "queue: false" option.

提交回复
热议问题