2012-08-15 119 views
2

这是我的代码片段。功能之间的延迟

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(); 

但它没有工作,我觉得我做错了这里,帮助将是非常很有帮助。

+2

A [现场演示](http://jsfiddle.net/)能重现问题很长的路要走为了得到我们的帮助,至少表明你愿意帮助我们来帮助你=) – 2012-08-15 09:55:25

回答

3

您可以使用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应用一些白魔法将该节点与您的内部的承诺链接起来。

演示http://jsfiddle.net/RGgr3/


貌似我做的一切都是正确的;)

+0

谢谢@jAndy,我明白了:) – ocinisme 2012-08-15 12:54:11

+0

如果我想要这个代码 $(“#card-6” ).delay(1000).rotate({角度:0}); 只有在customFadeOut结束后才能执行,我应该在哪里放置它? – ocinisme 2012-08-16 01:56:52