2011-08-27 22 views
3

這裏是我的html ...如何增量動畫6個盒子?

 <div class="project"> 
      <div class="box"> 

      </div> 
     </div> 
     <div class="project"> 
      <div class="box"> 

      </div> 
     </div> 
     <div class="project"> 
      <div class="box"> 

      </div> 
     </div> 
     <div class="project"> 
      <div class="box"> 

      </div> 
     </div> 
     <div class="project"> 
      <div class="box"> 

      </div> 
     </div> 
     <div class="project"> 
      <div class="box"> 

      </div> 
     </div> 

這裏是我的JavaScript ...

$('.box').each(function(){ 
      $(this).animate({ 
       width: 300, 
       height: 200, 
       top: 0, 
       left: 0 
      }, 500); 
     }); 

我希望每個框在一個接一個動畫。我可以專門做這件事,但代碼對於所有的回調都很長。想知道我如何正確地循環他們?

回答

2

你可以看看遞歸函數。

function animateBox(i) { 
    $('.box').eq(i).animate({ // animate this one 
        width: 300, 
        height: 200, 
        top: 0, 
        left: 0 
       }, 500, 
    function() { // when this one is complete 
     if($('.box').eq(i + 1).length > 0) { // if next one availabe 
      animateBox(i + 1); // call recursively for next one 
     } 
    }); 
} 

animateBox(0); // start process 

http://jsfiddle.net/pimvdb/753yU/

+0

感謝。這工作:)這是我想要做的。只是無法弄清楚正確的語法。 – Steven

+1

我改變它是自動執行... (功能animateBox(我){ \t \t \t $( '盒子')。等式(1).animate({//動畫這一 \t \t \t \t寬度:300, \t \t \t \t高度:200, \t \t \t \t頂部:0, \t \t \t \t左:0 \t \t \t},500, \t \t \t \t函數(){//當這一個是完整 \t \t \t \t如果($( '盒子')。等式(1 + 1)。長度> 0){/ /如果下一個速效 \t \t \t \t \t animateBox第(i + 1); //調用遞歸下一個 \t \t \t \t} \t \t \t}); \t \t})(0); – Steven

+0

@Steven:這是一個很好的。 – pimvdb

2

你可以用它全部變成你從這樣完成函數調用的函數。

function animateAll() { 
    var boxes = $(".box"); 
    if (boxes.length == 0) return; 

    function animateBox(n) { 
     $(boxes.get(n)).animate({ 
      width: 300, 
      height: 200, 
      top: 0, 
      left: 0 
     }, 500, function() { 
      ++n; 
      if (n < boxes.length) { 
       animateBox(n); 
      } 
     }); 
    } 

    animateBox(0); // start the first one 
} 
1

我花了一些時間,但我得到了它:)

Working Example

它使用遞歸函數來選擇行的下一個元素,如果該元素不存在,它會停止該功能。

代碼:

var i = 0; 

    function animate_next() { 
     if ($('.box:eq('+i+')').length == 0) { 
      return false; 
     } 
     $('.box:eq('+i+')').animate({ 
      width: 300, 
      height: 200, 
      top: 0, 
      left: 0 
     }, 500,function() { i++; animate_next(); }); 

    } 
    animate_next(); 
+1

不錯,如果你不知道,'.eq(i)'可能比':eq('+ i +') 。 – pimvdb

+1

我認爲如果結果集從一開始就儘可能窄,那麼最好。 –