2012-08-02 157 views
1

我試圖一個接一個地顯示元素......例如,如果div中有10個元素,我想要一個接一個顯示。但是一次只能有一個項目。我已經寫了下面的代碼,但預期它不工作..一個接一個顯示元素

function fades(c) { 
      var x = c; 
      c.fadeIn(3000, function() { 
       if (c.is('last-child')) { 
        c.fadeOut(3000); 
        fades(c); 
       } 
       else { 
        c.fadeOut(3000); 
        fades(c.next()); 
       } 
      }); 
    } 

感謝

+0

你可以設置一個的jsfiddle?它有助於瞭解結構和JS如何被稱爲 – Dunhamzzz 2012-08-02 10:52:27

+0

@Dunhamzzz請檢查http://jsfiddle.net/HTCa2/ – Exception 2012-08-02 11:06:48

回答

3

HTML

<div id="fades"> 
    <div>Hello #1</div> 
    <div>Hello #2</div> 
    <div>Hello #3</div> 
    <div>Hello #4</div> 
    <div>Hello #5</div> 
    <div>Hello #6</div> 
    <div>Hello #7</div> 
    <div>Hello #8</div> 
    <div>Hello #9</div> 
    <div>Hello #10</div> 
</div> 

的JavaScript

// First hide them all 
$("#fades div").hide(); 

function fades($div, cb) { 
    $div.fadeIn(100, function() { 
     $div.fadeOut(100, function() { 
      var $next = $div.next(); 
      if ($next.length > 0) { 
       fades($next, cb); 
      } 
      else { 
       // The last element has faded away, call the callback 
       cb(); 
      } 
     }); 
    }); 
} 

function startFading($firstDiv) { 
    fades($firstDiv, function() { 
     startFading($firstDiv); 
    }); 
} 

startFading($("#fades div:first-child")); 

這裏有一個小提琴:http://jsfiddle.net/VesQ/chw3f/5/

+0

它的完美..但是,您可以編輯以在DIV中的fadingOut最後一個元素之後再次顯示第一個元素。 – Exception 2012-08-02 11:17:20

+0

你可以自己做。在fadeOut回調中,在if(!$ div.is('last-child'))'之後添加一個「else」語句,然後用$(「#fades div:first-child)顯示第一個元素。 fadeIn()' – valscion 2012-08-02 11:21:58

+0

我試圖在其他條件'fades($(「#fades div:first-child」))中添加此代碼;'但它沒有工作..請檢查此http://jsfiddle.net/chw3f/2/ – Exception 2012-08-02 11:27:09

0

試試這個..

嘗試使用回調函數。回調函數在操作完成時執行。

function fades(c) { 
      var x = c; 
      c.fadeIn(3000, function() { 
       if (c.is('last-child')) { 
        c.fadeOut(3000, function() { 
         fades(c); 
        }); 

       } 
       else { 
        c.fadeOut(3000, function() { 
         fades(c.next()); 
        }); 
       } 
      }); 
    } 
+0

不工作..請檢查http://jsfiddle.net/HTCa2/ – Exception 2012-08-02 11:06:30