jQuery實現的打字機效果

 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>
相關文章
相關標籤/搜索