2012-08-15 210 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