jQuery实现逐字输入效果

之前做了个测试小游戏(姑且叫游戏吧)为了增加神秘性,就想给她加个逐字输入效果;刚好在网上找到一个挺好用的,于是就发扬拿来主义;按照自己的喜好做了一丢丢的修改强算是吧\( ̄︶ ̄)>

代码:

$.fn.autotype = function() {
    var _this=$(this);
    var str=_this.html();
    // 正则替换代码行之间添加的多个空格,不去除换行输出会有明显的停顿:实际是在输出多个空格
    str=str.replace(/(\s){2,}/g,"$1");
    var index = 0;
    $(this).html('');
    var timer = function() {
        var args=arguments;
        var current = str.slice(index, index+1);
        if (current == '<'){
            index = str.indexOf('>', index) + 1;
        }
        else{
          index++;
        }
        //位运算符: 根据setInterval运行奇偶次来判断是否加入下划线字符“|”,使输入效果更逼真
        if (index < str.length-1){
            //打印字符倒数第2个字符开始,不加“|”,以防止结束符可能会多输出“|”字符
            _this.html(str.substring(0, index) + (index & 1 ? '<span class="loop">|</span>' : ''));
        }else{
            _this.html(str.substring(0, index));
            return false;
        };
        // 延迟开始时间
        setTimeout(args.callee,150)
    };
    setTimeout(timer,1000);
};

 效果:

我也会有失望的时候

抱怨生活对我不够好

不能像电影一样

情节曲折结局依旧

出处:http://www.phpvar.com/archives/2865.html

原文地址:https://www.cnblogs.com/lilixing/p/4613617.html