0

我找到了这段代码,效果很好!但是当它到达最后一个字时,我该如何阻止它呢?

(function(){

    // List your words here:
    var words = [
        'awesome',
        'incredible',
        'cool',
        'fantastic'
        ], i = 0;

    setInterval(function(){
        $('#changerificwordspanid').fadeOut(function(){
            $(this).html(words[i=(i+1)%words.length]).fadeIn();
        });
       // 2 seconds
    }, 2000);

})();
4

2 回答 2

1

在开始动画代码之前,请检查数组中是否有单词,如果没有则停止间隔。

(function(){

// List your words here:
var words = [
    'awesome',
    'incredible',
    'cool',
    'fantastic'
    ], i = 0;

var interval = setInterval(function(){
    if(i+1 < words.length) {
        $('#changerificwordspanid').fadeOut(function(){
            $(this).html(words[i=(i+1)%words.length]).fadeIn();
        });
    } else {
        window.clearIntervall(interval);
    }
   // 2 seconds
}, 2000);

})();

清除间隔可以在这里找到:http: //de.selfhtml.org/javascript/objekte/window.htm#clear_interval

于 2013-10-01T13:28:21.607 回答
0

您可以通过这样做避免间隔,它将继续顺利添加单词。

(function(){

// List your words here:
var words = [
    'awesome',
    'incredible',
    'cool',
    'fantastic'
    ], i = 0;

(function loop(){
    $('#changerificwordspanid').fadeOut(function(){
        // send the loop function to fadeIn, It will exec when fadeIn complete
        $(this).html(words.shift()).fadeIn(loop);
    });
})();

})();

如果您还需要 2 秒延迟,则在每个淡入效果完成后。做这个

(function(){

// List your words here:
var words = [
    'awesome',
    'incredible',
    'cool',
    'fantastic'
    ], i = 0;

(function loop(){
    $('#changerificwordspanid').fadeOut(function(){
        // settimeout for 2 sec before called loop
        $(this).html(words.shift()).fadeIn(function(){
           setTimeout(loop, 2000);
        });
    });
})();

})();
于 2013-10-01T13:38:42.687 回答