2012-07-10 59 views
1

首先,我是比較新的JS都和jQuery,所以我提前道歉,如果這是一個非常愚蠢的問題。這就是說,在這裏它是: 我試圖創造,做一個慢「掃般」的轉變,從一個圖像到另一個背景的大炮般的動畫。 我遇到的最大問題是確保; a。增量計數器正在進行, b。圖像的每個「切片」在下一次開始之前完成其淡出。動畫一個jQuery設置一個對象在同一時間

如果有這樣做的一個簡單的(或明顯)的方式,我很樂意聽到它。爲了弄清爲什麼這些(以及其他類似的變化)不起作用,我一直在拉我的頭髮一段時間。

HTML: IMG類= 「BG」(這10個實例)

(function() { 
    // --- Variation 1 --- 

    function effect() { 
    var i = 0, 
    var current = $(".bg_1:eq(" + i + ")"), 
     arrLength = $(".bg_1").length; 
    while (i < arrLength) { 
     current.fadeOut(1000, 0); 
     i++; 
    } 

    } 
    effect(); 

    // --- Variation 2 --- 
    function effect() { 
    var i = 0, 
    var current = $(".bg_1:eq(" + i + ")"), 
     arrLength = $(".bg_1").length; 
    while (i < arrLength) { 
     current.fadeOut(1000, 0, function() { 
     i++; 
     }); 
    } 

    } 
    effect(); 

})(); 

我認爲它可以與 'I' 變量的範圍的問題,或在jQuery中衝突範圍的深度。任何可能的解決方案將非常感激!

謝謝。

回答

0

你的解決方案,同時動畫的所有圖片。您必須安裝一個recursive一連串的事件要做到這一點:

// initial count value declared outside the function to not reinitialize 
var count = 0; 
function effect() { 
    // search the current image 
    var current = $(".bg_1:eq(" + count + ")"); 
    // if there's an image, fade it out 
    if (current.length) { 
    current.fadeOut(1000, function() { 
    // increment the count; 
    count++; 
    // call the function recursively 
    effect(); 
    }); 
    } 
} 
// call the function 
effect(); 

看到它與工作JSFiddle here

+0

謝謝!這看起來與我之前嘗試過的東西非常相似。我一定會把訂單混在一起。你是冠軍。 – monners 2012-07-10 11:47:40

+0

不客氣!我只是用js小提琴更新了這篇文章,所以你可以看到它在行動。 – 2012-07-10 11:50:21

0

var current將永遠是相同的

試試這個:

function effect() { 
    var i = 0; 
    var arrLength = $(".bg_1").length; 
    while (i<arrLength) { 
     $(".bg_1:eq(" + i + ")").fadeOut(1000, 0); 
     i++; 
    } 

} 
effect(); 

只有現在它會像while循環一樣快速運行。這意味着它幾乎可以立即淡化所有的東西。你可能想運行一個setTimeout功能只要淡出雲:

var i = 0; 
setTimeout(function(){ 
    $(".bg_1:eq(" + i + ")").fadeOut(1000, 0); 
    i++; 
}, 1000); 

而且ofcourse您需要的時候到達最終將其復位。

編輯: 擊敗Richartz的方式,當fadeOut完成時再次運行該功能,甚至更好,然後setTimeout

1

沒有看到你的HTML,這是一個有點難以回答,但這裏的動畫序列的多個元素的一般方法:

(function _loop(idx) { 
    var $elements = $('#wrapper .bg'), idx = idx % $elements.length; 
    $elements.eq(idx).fadeIn('slow').delay(2500).fadeOut('slow', function() { 
     _loop(idx + 1); 
    }); 
}(0));​ 

演示:http://jsfiddle.net/UU5AM/

0

您可以使用fadeOutcallback說法爲它提供一個在動畫完成時執行的函數。你可以使用這個來提高計數器和(如果需要的話)爲下一個元素設置動畫。

例如:

(function() { 

    function effect() { 
    var i = 0, 
    var current = $(".bg_1:eq(" + i + ")"), 
     arrLength = $(".bg_1").length; 
    var animateNext = function() { 
     current.fadeOut(1000, 0, function() { 
     i++; 
     if (i < arrLength) { 
      animateNext(); 
     } 
     }); 
    } 
    animateNext(); 
    } 

    effect(); 

})(); 

正如你可以看到,我們已經存儲在animateNext可重複使用的功能。我們第一次在effect結束時稱它爲動畫串。之後,每個下一個動畫都從fadeOut的回調開始。

相關問題