Execute complete function only once in jQuery animation?

前端 未结 5 1969
一向
一向 2021-01-24 03:08

I\'m trying to animate the font size of some text:

$(\"p\").delay(500).animate({
    \"font-size\": \"+=50\"
}, 1000, function() {
    alert(\"Done\");
})​;


        
相关标签:
5条回答
  • 2021-01-24 03:49

    This code can be used as a generic 'countdown' type of function.

    // Function that returns a function,
    // which when invoked 'count' number of times,
    // will invoke the function 'fn'
    function runOnZero (count, fn) {
        return function () {
            if (--count <= 0) {
                fn();
            }
        };
    }
    
    // Get all the <p>s
    var ps = $("p");
    
    // Do your thing after ps.length calls
    var whenAllDone = runOnZero(ps.length, function () {
       alert("Done");
    });
    
    ps.delay(500).animate({
        "font-size": "+=50"
    }, 1000, whenAllDone)​;
    
    0 讨论(0)
  • 2021-01-24 03:54
    var $p = $("p");
    var lastIndex = $p.length - 1;
    
    $p.delay(500).animate({
        "font-size": "+=50"
    }, 1000, function() {
        if ($p.index($(this)) == lastIndex) {
            alert("Done");
        }
    })
    

    Demo

    0 讨论(0)
  • 2021-01-24 03:59

    You could just keep a flag, since they should animate simultaneously:

    var done = false;
    
    $("p").delay(500).animate({
        "font-size": "+=50"
    }, 1000, function() {
        if(!done) {
            done = true;
            alert("Done");
        }
    })​;
    

    Here's a demo.

    0 讨论(0)
  • 2021-01-24 04:03

    Give the P-tag in question an ID and select that ID rather than every P tag on the page. Like here: http://jsfiddle.net/LR8uP/1/

    Or if you want to animate every P-tag but run the function only once, add a state variable, like here: http://jsfiddle.net/LR8uP/2/

    0 讨论(0)
  • 2021-01-24 04:05

    Just to notice, you can also use a promise object:

    Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished.

    First example (demo):

    $("p").delay(500).animate({
        "font-size": "+=50"
    }, 1000).promise().done(function(){
        alert("done");
    });​
    

    Second example (demo):

    $.when($("p").delay(500).animate({
        "font-size": "+=50"
    }, 1000)).done(function(){
        alert("done");
    });​
    
    0 讨论(0)
提交回复
热议问题