JS特效——文字打印机

关键源码如下:

代码一

 1 <!doctype html>
 2 <html lang="en">
 3  <head>
 4   <meta charset="UTF-8">
 5   <meta name="Generator" content="EditPlus®">
 6   <meta name="Author" content="">
 7   <meta name="Keywords" content="">
 8   <meta name="Description" content="">
 9   <title>Document</title>
10   <style>
11     *{margin:0;padding:0;}
12     body{background:#f9c;}
13     #show-text{width:150px;margin:20px auto;}
14     h1{text-align:center;color:white;}
15  </style>
16  </head>
17  <body> 
18  <h1>input your text</h1>
19  <div id="show-text">
20     <p  style="color:white;font-size:14px;font-family:'微软雅黑';"><span id="bbb"></span><span id="gb">_<span></p>
21 </div>
22 
23 <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
24 <script type="text/javascript"> 
25 var text="静坐长思往日回,岁月蹉跎徒伤悲。小荷才露尖尖角,初设江湖岁月催。壮志未酬心犹在,琐事绕身家待归。日月虽往随心欲,梦里千回展翅飞。"
26    
27 function printer(text){ 
28     var l = text.length;
29     var t = 0;
30     var arr = [];    
31     for(var i = 0; i < l; i++){    
32     arr[i] = text.substr(i,1);    
33     }      
34     setInterval(function(){ $("#gb").fadeOut(100).fadeIn(100); },300); 
35     var init = setInterval(function(){
36     if(t < l){    
37         $("#bbb").append(arr[t]);
38         if((t!==(l-1))&&(t%8==7)){
39             $("#bbb").append('<br/>');
40         }    
41         t++;    
42         }else{
43        clearInterval(init);            
44         }
45 },500);
46         
47 }
48 
49     printer(text);
50 </script>
51  </body>
52 </html>

 效果预览:点击Mygithub

代码二

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
<style>
*{margin:0;padding:0;}
.text{500px;margin:30px auto;color:white;}
body{background:#c6f;}
p{text-indent:2em;}
</style>
<script>
function text(str){
var arr=[];
var text=document.getElementsByClassName("text")[0];
for(var i=0;i<str.length;i++){arr[i]=str[i];}
var p=document.getElementById("sp1");
var sp2=document.getElementById("sp2");
setInterval(function(){sp2.style.display="none";setTimeout("sp2.style.display='inline'",500);},700);
var index=0;
var obj=setInterval(function(){
if(index<arr.length){
var text=document.createTextNode(arr[index]);
}
p.appendChild(text);
index++;
},400);

}
window.onload=function(){
text("有时候,其实害怕寂寞,但又卟想去打扰别人的幸福;有时候,明明很想哭泣 却又怕眼泪从眼裏掉进心裏;有时候,很想像颗流星,即使生命只有一瞬,却我可以让爱我的和不爱我的人永远记起。其实我可以更加的勇敢去接受那些曾经的回忆,只是那是时间的车轮底,被风一吹,留不下痕迹 却伤了心,踮起脚看到窗外的云。或许它一会儿也会被别人看见,只是,他们看到的只是云,却看不到云裏带走了某人的一段记忆,感伤於此,忧伤继续……");
}
</script>

</head>
<body>
<div class="text"><p >_</span></p></div>
</body>
</html>

 效果预览:点击Mygithub