2012-02-23 70 views
0

我試圖淡入/出div內的一些文本。爲了調試的目的,我已經把時間保持得很快。問題是我認爲淡入淡出是互相爭鬥的。有時文本進行更新,然後將其淡入/出...有一些setInterval + JQuery FadeIn/FadeOut問題

See this interactive example on jsFiddle

下面的代碼:

var tips = [ 
    'AAA', 
    'BBB', 
    'CCC' 
]; 

var currentTipIndex = 0; 
setInterval(function() { 
    currentTipIndex++; 
    if (currentTipIndex >= tips.length) { 
     currentTipIndex = 0; 
    } 
    $("#pewpew").fadeOut(1000); 
    $("#pewpew").html(tips[currentTipIndex]); 
    $("#pewpew").fadeIn(1000); 
}, 1 * 5 * 1000);​ 

這就像要間隔計時器停止。然後淡出。 (等待淡出完成)。更新文本。淡入..(等待淡入開始)。然後再次啓動計時器。

任何人都可以幫忙嗎?

+0

使用回調函數與淡出和淡入。見http://api.jquery.com/fadeIn/ – Stefan 2012-02-23 08:19:59

回答

2

更新:

// Rotating Tips. 
var tips = ['AAA', 'BBB', 'CCC']; 

var currentTipIndex = 0; 

function recursiveTimeout() { 
    setTimeout(function() { 
     currentTipIndex++; 
     if (currentTipIndex >= tips.length) { 
      currentTipIndex = 0; 
     } 
     $("#pewpew").fadeOut(1000, function() { 
      $("#pewpew").html(tips[currentTipIndex]); 
     }); 

     $("#pewpew").fadeIn(1000, recursiveTimeout()); 
    }, 1 * 5 * 1000); 

}; 
recursiveTimeout(); 

使用淡出回調確保在動畫加載內容之前完成。然後在fadeIn中創建一個遞歸回調,當它完成時啓動定時器。

更新的小提琴:http://jsfiddle.net/ZCadu/2/

+0

這個答案幫助我的情況@ infra-stank謝謝!我很好奇,至於爲什麼你在fadeIn回調函數定時器上乘以1而不是5 * 1000? * noob問題:P – Froy 2016-03-30 17:29:49

0

試試這個,

var tips = [ 
    'AAA', 
    'BBB', 
    'CCC' 
]; 

function fadeIn(html) { 
    $("#pewpew").html(html); 
    $("#pewpew").fadeIn(1000, function() { 
     $("#pewpew").fadeOut(1000, getNextTip); 
    }); 
} 

var currentTipIndex = 0; 
function getNextTip() { 
    if (currentTipIndex >= tips.length) 
     currentTipIndex = 0; 

    var cTip = tips[currentTipIndex]; 
    fadeIn(cTip); 

    currentTipIndex++; 
} 

$(function() { 
    getNextTip(); 
}); 
​