简体   繁体   English

循环jquery中的打字机效果-如何

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

I am trying to achieve a typewriter effect in jQuery and this is what I have achieved so far. 我正在尝试在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);
});

This is give the effect one time, but I want it to run in a loop continuously. 这是一次效果,但我希望它连续不断地运行。

I have set up a fiddle for what I have tried so far here 我已经为到目前为止在这里所做的尝试设置了一个小提琴

Thanks for looking 谢谢看

Just maintain a counter, and reset to 0 at the end of the string. 只需维护一个计数器,然后在字符串末尾重置为0

DEMO: http://jsfiddle.net/QPNTq/ 演示: 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);

No need for .each() or any other kind of loop this way. 这样就不需要.each()或任何其他类型的循环。 Much simpler. 简单得多。

Wrap your code within a function (something named repeat ) and then call it using setInterval like 将代码包装在一个函数中(称为repeat ),然后使用setInterval调用它,例如

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

JSFiddle 的jsfiddle

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