1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"><head> 3 <meta http-equiv="Content-Type" content="text/html; charset=gbk"> 4 <title>简易网页时钟</title> 5 <style type="text/css"> 6 body,div{margin:0;padding:0;} 7 body{color:#fff;font:16px/1.5 5fae8f6f96c59ed1;} 8 #clock{width:300px;text-align:center;background:#1a1a1a;margin:10px auto;padding:20px 0;} 9 span{color:#000;width:80px;line-height:2;background:#fbfbfb;border:2px solid #b4b4b4;margin:0 10px;padding:0 10px;} 10 11 </style> 12 </head> 13 <body> 14 <div id="clock"> 15 <span>1</span>点 16 <span>1</span>分 17 <span>1</span>秒 18 </div> 19 <script type="text/javascript"> 20 window.onload = function(){ 21 var spans = document.getElementById("clock").getElementsByTagName("span"); 22 23 //第一种方式,直接创建对象,获取时分秒,赋值即可 24 //function getTime(){ 25 // var now = new Date(); 26 // spans[0].innerHTML = now.getHours(); 27 // spans[1].innerHTML = now.getMinutes(); 28 // spans[2].innerHTML = now.getSeconds(); 29 //} 30 //setInterval(getTime,1000); 31 function getTime(){ 32 var now = new Date(); 33 var aList = [now.getHours(),now.getMinutes(),now.getSeconds()]; 34 for(p in aList)spans[p].innerHTML = format(aList[p]); 35 } 36 getTime(); 37 setInterval(getTime,1000); 38 function format(a){ 39 return a.toString().replace(/^(d)$/,"0$1"); 40 } 41 } 42 </script> 43 </body> 44 </html>