本文實例講述了JS實現的打字機效果。分享給大家供大家參考,具體如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame Remove this if you use the .htaccess --> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>JS打字機效果</title> <meta name="description" content=""> <meta name="author" content="Administrator"> <meta name="viewport" content="width=device-width; initial-scale=1.0"> <!-- Replace favicon.ico & apple-touch-icon.png in the root of your domain and delete these references --> <style type = "text/css"> #main { width: 80%; height: 750px; margin: auto; padding: 10px; background: #cfe1ca; border: 10px outset #f9c6aa; line-height: 30px; color: #9f3c61; font-size: 18px; } p { text-indent: 30px; } </style> <script type = "text/javascript"> var typeWriter = { msg: function(msg){ return msg; }, len: function(){ return this.msg.length; }, seq: 0, speed: 150,//打字時間(ms) type: function(){ var _this = this; document.getElementById("main").innerHTML = _this.msg.substring(0, _this.seq); if (_this.seq == _this.len()) { _this.seq = 0; clearTimeout(t); } else { _this.seq++; var t = setTimeout(function(){_this.type()}, this.speed); } } } window.onload = function(){ alert("welcome to http://www.jb51.net") var msg = "JS打字機效果 ,原理很簡單:每次多獲取一個待打出的字符串的值,輸出,覆蓋原來輸出的內容即可"; function getMsg(){ return msg; } typeWriter.msg = getMsg(msg); typeWriter.type(); } </script> </head> <body> <div id = "main"> </div> </body> </html>
更多關於JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript切換特效與技巧總結》、《JavaScript查找算法技巧總結》、《JavaScript動畫特效與技巧匯總》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。