2012-02-23 71 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(); 
}); 
​