遇到一些setInterval + JQuery FadeIn / FadeOut的问题

时间:2012-02-23 08:17:16

标签: javascript jquery timer setinterval

我试图在div中淡入/淡出一些文本。为了调试目的,我一直保持快速的时间。问题是,我认为淡入淡出是相互争斗的。有时文本会更新,然后它会淡入/淡出......

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

就像想要间隔计时器停止一样。然后消失。 (等待淡出完成)。更新文字。淡入..(等待淡入开始)。然后再次启动计时器。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分: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();

使用fadeOut回调可确保在加载内容之前动画已完成。然后在fadeIn中创建一个递归回调,在计时器完成时启动它。

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

答案 1 :(得分: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();
});
​
相关问题