2009-05-06 117 views
3

我逐漸淡化元素,但它似乎一下子全部消失。jQuery同步操作

如何逐個淡化元素。只有一個人完全消失,第二個人才會開始消失。

我環路和褪色像這樣

$(ele).fadeIn('slow'); 

回答

3

我製作了這個快速/簡單的jQuery插件,可以讓您按照自己的意願進行操作。 :-)

$.fn.extend({ 
    serial_fade: function(o) { 
     if(!o.speed || o.speed == undefined || o.speed == null) { o.speed = 'slow'; } 
     if(!o.fade || o.fade == undefined || o.fade == null) { o.fade = 'in'; } 
     if(!o.index || o.index == undefined || o.index == null) { o.index = 0; } 
     var s = this.selector; 
     if(o.fade.toLowerCase() == 'in') { 
      return this.eq(o.index).fadeIn(o.speed, function() { 
       o.index++; 
       if($(s).eq(o.index).length > 0) { 
        $(s).serial_fade({speed:o.speed,fade:o.fade,index:o.index}); 
       } 
      }); 
     } else { 
      return this.eq(o.index).fadeOut(o.speed, function() { 
       o.index++; 
       if($(s).eq(o.index).length > 0) { 
        $(s).serial_fade({speed:o.speed,fade:o.fade,index:o.index}); 
       } 
      }); 
     } 
    } 
}); 

// To call it just do this: 
$(ele).serial_fade({speed:'slow',fade:'in'}); 

// Optionally, you can pass which element you want to start with (0-based): 
$('a').serial_fade({speed:'slow',fade:'in',index:2}); 

// If you want to start with element 2 (3, really) and fade all the rest *out* 
// sequentially, verrry slowly: 
$(ele).serial_fade({speed:5000,fade:'out',index:2}); 

它應該像任何其他jQuery方法一樣使用任何類型的選擇器。我希望這能爲你解決。

編輯:我延長,以便它可以做淡入褪色出局了。它似乎更有用的方式...

4

淡入有完成衰落時執行的回調。添加到elemX類的每個元素,其中x是衰落的順序。然後使用下面的代碼:

startFading(1); 

function startFading(order) { 
    $(".ele" + order).fadeIn('slow', function() { 
     if (order < orderMax) { 
      startFading(order+1); 
     } 
    }); 
} 
+0

JavaScript中的遞歸!非常好。 – montrealist 2009-05-06 13:28:52

+0

謝謝,這可以替換爲同一類的元素。我看到你在使用訂單。然而,這可以通過類 – Hitz 2009-05-06 14:05:34

0

你可以使這個通用的,而不是強迫它只是爲了淡化。

function depth(collection, fun, i) { 
    if (i === undefined) 
     depth(collection, fun, 0); 
    else 
     if (i < collection.length) 
      fun(collection[i], function(){ 
       depth(collection, fun, i + 1); 
      }); 
}; 

depth($("a"), function(elem, fun) { 
    $(elem).fadeIn('slow', fun); 
});