2011-10-03 94 views
2

這段代碼似乎打破了我的代碼的其餘部分?jquery重複動畫

function sam() { 
    $("#animate").children("#box") 
     .animate({ 
     left: '+=1100'},8000, 'linear', function() { 
      $("#animate").children("#box").css("left", "0"); 
      sam(); 
     }); 
} 

setInterval(sam()); 

很抱歉的短的響應,但我一直得到用封笨質量消息

+0

什麼是「打破的其餘部分我代碼「的意思? – JJJ

+0

它只是停止我的代碼的其他部分在Firefox中工作? –

回答

8

嘗試改變

setInterval(sam()); 

setInterval(function(){ 
    sam() 
}, 1000); 

將觸發SAM()每秒。您的setInterval使用錯誤

另外,刪除sam()調用sam()函數。

所以最終代碼:

function sam() { 
    $("#animate").children("#box") 
     .animate({ 
     left: '+=1100'},8000, 'linear', function() { 
      $("#animate").children("#box").css("left", "0"); 
     }); 
} 

setInterval(function(){ 
    sam() 
}, 1000); 
+0

也不需要調用sam()遞歸,因爲setInterval會照顧重複的執行 –

+0

@MohamedAli:好趕上 – genesis

1

setInterval需求你要多長時間運行的代碼SAM()第二個參數。但是我不知道你是否想要那樣,反正它似乎是這樣做的。

function sam() { 
    $("#animate").children("#box") 
     .animate({ 
      left: '+=1100'},8000, 'linear', function() { 
      $("#animate").children("#box").css("left", "0"); 
      sam(); 
     }); 
} 

sam(); 

,如果你想一遍又一遍重複的動畫,或使用setTimeout的,而不是setInterval的,應足夠多。

即使第一次運行沒有完成,您的動畫也需要8秒,如果您說每2秒運行一次sam(),例如您會得到一個非常非常糟糕的結果,因爲代碼需要超過2秒運行,你也說它應該重新運行。我根本不會使用setInterval

演示:http://jsfiddle.net/voigtan/tG7Gm/2/

+0

我不知道爲什麼,但上述不起作用 –

+0

似乎工作:http://jsfiddle.net/ voigtan/tG7Gm/1 /你的標記是怎樣的? – voigtan

0

你可以使用成品動畫回調,開始一個新的動畫。你能澄清一下,如果你想動畫開始時,第一個完成,或只是有無盡的動畫在彼此之上?

+0

我想讓動畫不斷重複 –

+0

什麼是完成的動畫回調? –

+0

對不起,花了這麼長時間。請閱讀此處:http://api.jquery.com/animate/基本用法下的第二個示例。 – OptimusCrime

0

從您通過sam的位置刪除()作爲回調。你想傳遞函數,而不是它的結果。

var sam = function() { // Changed this to show functions are variables 
    $("#animate").children("#box") 
     .animate({ 
     left: '+=1100'},8000, 'linear', function() { // Not sure about += 
      $("#animate").children("#box").css("left", "0"); 
      sam; // Pass the variable, not the result of the function 
     }); 
}; 
sam(); // Call the function the first time. 

然而,我注意到,#box是一個id。所以,我推測什麼,我認爲你想做的事,並想出這個演示:

var sam = function() { // Changed this to show functions are variables 
 
    $("#box").animate({left: $("#animate").width() + 'px'}, 1000, 'linear') 
 
      .animate({left: '-' + $("#box").width() + 'px'}, 0, 'linear', sam); 
 
}; 
 
sam(); // Call the function the first time.
#animate { 
 
    position: relative; 
 
    width: 200px; 
 
    height: 200px; 
 
    background-color: red; 
 
    overflow: hidden; 
 
} 
 
#box { 
 
    position: absolute; 
 
    width: 50px; 
 
    height: 50px; 
 
    left: 0; 
 
    top: 0; 
 
    background-color: blue; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div id="animate"> 
 
    <div id="box"></div> 
 
</div>

或者的jsfiddle如果你喜歡:http://jsfiddle.net/Gisleburt/tn8j7w8p/1/