<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>javascript打字机效果</title> <style type="text/css"> *{margin:0;padding:0;} body{margin:50px;background:#181818;} #display{padding:10px;width:500px;height:200px;background:#666;font:14px/28px verdana;text-indent:2em;color:#eee;} </style> <script type="text/javascript"> var i = 0; var str = "对于一个网页制作者来说,对HTML语言一定不会感到陌生,因为HTML语言是所有网页制作的基础。但是如果页面能够方便网友们的使用,友好而大方,甚至像桌面应用程序一样,那么仅仅依靠HTML语言是不够的,JavaScript在这其中扮演着重要的角色。"; window.onload = function typing(){ var mydiv = document.getElementById("display"); mydiv.innerHTML += str.charAt(i); i++; var id = setTimeout(typing,30); if(i==str.length){ clearTimeout(id); //alert("程序执行完毕!"); } } </script> </head> <body> <div id="display"></div> </body> </html>
呵呵,感觉蛮有趣的,其实字并不是一个个"打"出来的,而是通过charAt不断获取加上去的,在typing里用setTimeout不断调用其自身,每执行一次i就加1,if(i==字符串的长度),clearTimeout(timeoutID)。。。