1 <!doctype html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title>基于jQuery实现的打字机效果</title>
6 <script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
7 <style>
8 </style>
9 </head>
10 <body>
11 <div class="autotype" id="autotype">
12 <p>一场雨把我困在这里</p>
13 <br>
14 <p>你温柔的表情</p>
15 <p>会让我伤心</p>
16 <br>
17 <p>六月的雨,只是无情的你~</p>
18 </div>
19
20 <script>
21 $.fn.autotype = function() {
22 var $text = $(this);
23 console.log('this', this);
24 var str = $text.html(); //返回被选 元素的内容
25 var index = 0;
26 var x = $text.html('');
27 //$text.html()和$(this).html('')有区别
28 var timer = setInterval(function() {
29 //substr(index, 1) 方法在字符串中抽取从index下标开始的一个的字符
30 var current = str.substr(index, 1);
31 if (current == '<') {
32 //indexOf() 方法返回">"在字符串中首次出现的位置。
33 index = str.indexOf('>', index) + 1;
34 } else {
35 index++;
36 }
37 //console.log(["0到index下标下的字符",str.substring(0, index)],["符号",index & 1 ? '_': '']);
38 //substring() 方法用于提取字符串中介于两个指定下标之间的字符
39 $text.html(str.substring(0, index) + (index & 1 ? '_': ''));
40 if (index >= str.length) {
41 clearInterval(timer);
42 }
43 },
44 100);
45 };
46 $("#autotype").autotype();
47 </script>
48
49 </body>
50 </html>