Stopping specific jQuery animations

前端 未结 5 686
一整个雨季
一整个雨季 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

    After thinking about this a little harder about this, I realized that what you're trying to do isn't easy doable because of the way animations are handled in jQuery.

    Since animations are managed by a queue, it not possible to run concurrent animations on the same element without them being in the same function.

    That is to say,

    $(element).animate(aThing, aTime);
              .animate(anotherThing, anotherTime);
    

    isn't going to run in parallel. aThing will finish in aTime, followed by anotherThing lasting for anotherTime.

    Thus, you can only accomplish multiple changes by having them in the same function:

    $(element).animate({aThing: aValue, anotherThing: anotherValue}, aTime);
    

    Here's a quick explanation of the anatomy of how animation functions are handled within jQuery.

    A timer object is assigned to the element for the duration of the animation:

    function t( gotoEnd ) {
        return self.step(gotoEnd);
    }
    
    t.elem = this.elem;
    jQuery.timers.push(t);
    

    When you call the stop function, it removes the timer from timers:

    // go in reverse order so anything added to the queue during the loop is ignored
    for ( var i = timers.length - 1; i >= 0; i-- ) {
        if ( timers[i].elem === this ) {
            if (gotoEnd) {
                // force the next step to be the last
                timers[i](true);
            }
    
            timers.splice(i, 1);
        }
    }
    

    So, there is no way to remove a specific property of an animation function since the timer itself is killed.


    The only way I could think of accomplishing this would be to keep track of the start time and duration, re-enqueuing the animation and stopping the current one.

    var start = $.now();
    var duration = 5000;
    
    $(element).animate({opacity: '0.5', width: '500px'}, duration);
    

    ...

    var remaining = duration - ($.now() - start);
    $(element).animate({opacity: '0.5', remaining)
              .stop();
    

提交回复
热议问题