<!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>date</title> <style type="text/css"> #mytime{width:230px;height:30px;background:#4ba800;font:13px/30px tahoma;color:#fff;text-align:center;} </style> <script type="text/javascript"> window.onload = function startTime(){ var t = new Date(); var year = t.getFullYear(); var month = t.getMonth()+1; var date = t.getDate(); var day = t.getDay(); var hour = t.getHours(); var minute = t.getMinutes(); var second = t.getSeconds(); var dayArr = ["日","一","二","三","四","五","六"]; if(hour<10){hour = "0" + hour} if(minute<10){minute = "0" + minute} if(second<10){second = "0" + second} document.getElementById("mytime").innerHTML = year + "年" + month + "月" + date + "日 " + "星期" +dayArr[day] + " " + hour + " : " + minute + " : " + second; setTimeout(startTime,1000); } </script> </head> <body> <div id="mytime"></div> </body> </html>
在这里记录一下吧,想想以前都是到网上复制别人的,总是这错那错,也不知个所以然,现在懂了一点点的js,就自己动手敲了敲,不过我在想用if判断去添加0这样写是不是效率有点低呢,能想到的也只是这样了,先这样吧,呵呵。。。
对了,这里是在window.onload里用setTimeout重复调用startTime()函数,也就是重复调用其自身吧,当然我们也可以用setInterval(startTime,1000)方法,millisec如果设置为1000的话页面载入时会有1秒钟的延迟,那就把值设置小一点吧,,,