簡體   English   中英

循環jquery中的打字機效果-如何

[英]Typewriter effect in a loop jquery - How to

我正在嘗試在jQuery中實現打字機效果,這是我到目前為止所實現的。

var text = 'Loading ...';

//text is split up to letters
$.each(text.split(''), function(i, letter){

    //we add 100*i ms delay to each letter 
    setTimeout(function(){

        //we add the letter to the container
        $('#container').html($('#container').html() + letter);

    }, 100*i);
});

這是一次效果,但我希望它連續不斷地運行。

我已經為到目前為止在這里所做的嘗試設置了一個小提琴

謝謝看

只需維護一個計數器,然后在字符串末尾重置為0

演示: http : //jsfiddle.net/QPNTq/

var chars = 'Loading ...'.split('');
var container = document.getElementById("container");

var i = 0;
setInterval(function () {
    if (i < chars.length) {
        container.innerHTML += chars[i++];
    } else {
        i = 0;
        container.innerHTML = "";
    }
}, 100);

這樣就不需要.each()或任何其他類型的循環。 簡單得多。

將代碼包裝在一個函數中(稱為repeat ),然后使用setInterval調用它,例如

setInterval(function () {
    $('#container').html(''); //clear the container
    repeat();
}, 1100)

的jsfiddle

的jsfiddle

var text = 'Loading ...';

setInterval(function(){

$('#container').html("");

//text is split up to letters
    $.each(text.split(''), function(i, letter){

        //we add 100*i ms delay to each letter 
        setTimeout(function(){

            //we add the letter to the container
            $('#container').html($('#container').html() + letter);

        }, 100*i);
    });

}, 1000);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM