这是我的代码片段。
function customFadeIn () {
$("img.imgKit").each(function(index) {
$(this).delay(1000*index).fadeIn("slow");
});
console.log("one runs");
}
function customFadeOut () {
$("img.imgKit").each(function(index) {
$(this).delay(1000*index).not(document.getElementById('card-6')).fadeOut("slow" , function () {
$("#card-6").delay(1000).rotate({angle:0});
});
});
console.log("two runs");
}我希望customFadeOut只在customFadeIn完成后运行,因此我这样调用它
customFadeIn();
customFadeOut();但是它没有起作用,我想我在这里做错了什么,如果能帮上忙的话会很有帮助。
发布于 2012-08-15 17:56:50
您可以使用jQuerys Deferred / promise对象。动画也“继承”这些对象,你可以应用jQuery.when()来拍摄多个完成的承诺。
有几种方法可以为此重新构造代码,其简单实现可能如下所示:
(function() {
var promises = [ ];
function customFadeIn () {
$("img.imgKit").each(function(index) {
promises.push( $(this).delay(1000*index).fadeIn("slow").promise() );
});
}
function customFadeOut () {
jQuery.when.apply( null, promises ).done(function() {
$("img.imgKit").each(function(index) {
$(this).delay(1000*index).not(document.getElementById('card-6')).fadeOut("slow" , function () {
$("#card-6").delay(1000).rotate({angle:0});
});
});
console.log("two runs");
});
}
}());如果我没有做错任何事情,customFadeOut会设置一个侦听器,在运行自己的代码之前等待所有动画/承诺完成。最后,您甚至不必显式地调用.promise()方法,jQuery应用了一些白魔法,将该节点与内部的promise链接起来。
演示:http://jsfiddle.net/RGgr3/
看起来我做的一切都是正确的;)
https://stackoverflow.com/questions/11967263
复制相似问题