如何在jquery中重复一个句子

时间:2014-11-25 21:49:57

标签: javascript jquery

我有这个jquery脚本,逐句显示句子中的每个单词。

http://jsfiddle.net/9tvd3ybg/

$(function (){    

var str = "It was a dark and stormy night in the Bay of Biscay, and the Captain and his sailors were seated around the fire. Suddenly, one of the sailors said, Tell us a story, Captain. And the Captain began, ";

var spans = '<span>' + str.split(/\s+/).join(' </span><span>') + '</span>';

$(spans).hide().appendTo('.text').each(function(i){
        $(this).delay(100 * i).fadeIn(100);

});

});

我希望句子一遍又一遍地重复,每次都要追尾,即

在比斯开湾,这是一个黑暗而暴风雨的夜晚,船长和他的船员坐在火炉旁。突然,其中一名水手说,告诉我们一个故事,船长。船长开始了,在比斯开湾是一个黑暗而暴风雨的夜晚,船长和他的船员坐在火炉旁。突然,其中一名水手说,告诉我们一个故事,船长。船长开始了,.......

不确定如何实现这一目标。我尝试过.promise和.delay没有成功。任何帮助将不胜感激,谢谢。

2 个答案:

答案 0 :(得分:3)

使用您提供的代码进行简单的超时:

var populateSentence = function () {
    $(spans).hide().appendTo('.text').each(function (i) {
        $(this).delay(100 * i).fadeIn(100);
        if (i === ($(spans).length - 1)) {
            setTimeout(function () {
                populateSentence();
                // timeout set to account for fade in delay
            }, $(spans).length * 100);
        }
    });
};
populateSentence();

Here is a Fiddle

答案 1 :(得分:1)

试试这个:

var str = "It was a dark and stormy night in the Bay of Biscay, and the Captain and his sailors  were seated around the fire. Suddenly, one of the sailors said, Tell us a story, Captain. And the Captain began, ".split(/\s/);

var i = 0;
setInterval(function() {
    $('<span></span>').text(str[i]).hide().appendTo('.text').fadeIn(100);
    i = (i + 1) % str.length;
}, 100);