A-A+
jquery实现自动逐字打印效果(像黑客电影一样)
看过国外有关电脑黑客的电影都看到过这样的场景:黑客高手在电脑前一阵狂敲键盘,电脑屏一串串代码就出来,然后就显示黑客已经黑进系统,已做完该做的事啦。那么电影演员是如何做到这一步的呢?以下是用jq的模拟。
为了在这重现黑客的神奇功力是怎么做到的,我们来解密下这逼真效果的实现方法,代码如下:
- <div id="autotype">
- <p>two_step_auth_command.bui</p>
- <br>
- <p>for agent 54348</p>
- <p>中文文字测试测试</p>
- </div>
- <script>
- $.fn.autotype = function() {
- var _this=$(this);
- var str=_this.html();
- // 正则替换代码行之间添加的多个空格,不去除换行输出会有明显的停顿:实际是在输出多个空格
- strstr=str.replace(/(s){2,}/g,"$1");
- var index = 0;
- $(this).html('');
- var timer = function() {
- var args=arguments;
- var current = str.slice(index, index+1);
- // html标签完整输出,如:<p>
- if (current == '<'){
- index = str.indexOf('>', index) + 1;
- }
- else{
- index++;
- }
- //位运算符: 根据setInterval运行奇偶次来判断是否加入下划线字符“_”,使输入效果更逼真
- if (index < str.length-1){ //打印字符倒数第2个字符开始,不加下划线字符,以防止结束符可能会多输出一下划线字符
- _this.html(str.substring(0, index) + (index & 1 ? '_' : ''));
- }else{
- _this.html(str.substring(0, index));
- clearTimeout(timer);
- };
- setTimeout(args.callee,70)
- };
- // 延迟1s开始
- setTimeout(timer,1000);
- };
- $("#autotype").autotype();
- </script>