2012-02-23 6 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

答えて

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コールバック関数のタイマーで5 * 1000の代わりに1を掛ける理由は? * noob質問:P – Froy

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(); 
}); 
​