A-A+

jquery实现自动逐字打印效果(像黑客电影一样)

2016年01月09日 前端设计 暂无评论 阅读 6 views 次

看过国外有关电脑黑客的电影都看到过这样的场景:黑客高手在电脑前一阵狂敲键盘,电脑屏一串串代码就出来,然后就显示黑客已经黑进系统,已做完该做的事啦。那么电影演员是如何做到这一步的呢?以下是用jq的模拟。

为了在这重现黑客的神奇功力是怎么做到的,我们来解密下这逼真效果的实现方法,代码如下:

  1. <div id="autotype">  
  2.     <p>two_step_auth_command.bui</p>  
  3.     <br>  
  4.     <p>for agent 54348</p>  
  5.     <p>中文文字测试测试</p>  
  6. </div>  
  7. <script>  
  8.     $.fn.autotype = function() {  
  9.       var _this=$(this);  
  10.       var str=_this.html();  
  11.       // 正则替换代码行之间添加的多个空格,不去除换行输出会有明显的停顿:实际是在输出多个空格  
  12.       strstr=str.replace(/(s){2,}/g,"$1");  
  13.         var index = 0;  
  14.         $(this).html('');  
  15.         var timer = function() {  
  16.             var args=arguments;  
  17.             var current = str.slice(index, index+1);  
  18.             // html标签完整输出,如:<p>  
  19.             if (current == '<'){  
  20.                 index = str.indexOf('>', index) + 1;  
  21.             }  
  22.             else{  
  23.             index++;  
  24.             }  
  25.             //位运算符: 根据setInterval运行奇偶次来判断是否加入下划线字符“_”,使输入效果更逼真  
  26.             if (index < str.length-1){ //打印字符倒数第2个字符开始,不加下划线字符,以防止结束符可能会多输出一下划线字符  
  27.                 _this.html(str.substring(0, index) + (index & 1 ? '_' : ''));  
  28.             }else{  
  29.                 _this.html(str.substring(0, index));  
  30.                 clearTimeout(timer);  
  31.             };  
  32.             setTimeout(args.callee,70)  
  33.         };  
  34.         // 延迟1s开始  
  35.         setTimeout(timer,1000);  
  36.     };  
  37.     $("#autotype").autotype();  
  38. </script>  
标签:

给我留言