admin管理员组文章数量:1277895
I'm trying to animate the font size of some text:
$("p").delay(500).animate({
"font-size": "+=50"
}, 1000, function() {
alert("Done");
});
Here's a demo.
I want to do something after animating the <p>
s, which in the example is alert
, but it surprisingly runs it for each <p>
, and that's not what I want. Is there a possible way to make it just run once or is it not possible?
I'm trying to animate the font size of some text:
$("p").delay(500).animate({
"font-size": "+=50"
}, 1000, function() {
alert("Done");
});
Here's a demo.
I want to do something after animating the <p>
s, which in the example is alert
, but it surprisingly runs it for each <p>
, and that's not what I want. Is there a possible way to make it just run once or is it not possible?
5 Answers
Reset to default 10Just 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");
});
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
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.
Give the P-tag in question an ID and select that ID rather than every P tag on the page. Like here: http://jsfiddle/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/LR8uP/2/
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);
本文标签: javascriptExecute complete function only once in jQuery animationStack Overflow
版权声明:本文标题:javascript - Execute complete function only once in jQuery animation? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741293694a2370695.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论