将打字机jQuery效果逐字逐句改为

时间:2012-11-26 00:07:28

标签: javascript jquery

这个jQuery函数逐字逐句地运行,但我似乎无法让它逐字逐句。

任何想法,这是功能:

//Typewriter Effect
$.fn.Typewriter = function(opts){
    var $this = this,
        defaults = { animDelay: 50 },
        settings = $.extend(defaults, opts);
    $.each(settings.text, function(i, letter){
        setTimeout(function(){
            $this.html($this.html() + (letter!='\n'?letter:'<br />'));
        }, settings.animDelay * i);
    });
}

谢谢!

1 个答案:

答案 0 :(得分:0)

请勿使用$.each来迭代字符串,并使用.text来设置文字而不是.html

要将效果从单个字符更改为整个单词,只需将split输入文字转换为单词:

$.fn.Typewriter = function(opts){
    var $this = this,
        defaults = { animDelay: 50 },
        settings = $.extend(defaults, opts),
        words = settings.text.split(/(?=\s)/), // split before every whitespace
        i = 0;
    function animate() {
        if (i==words.length) return;
        $this.text(words.slice(0, i++).join(''));
        setTimeout(animate, settings.animDelay);
    }
    animate();
}