简单的网页数字时钟
主要实现思路:利用JavaScript内置对象Date来获取当前系统时间,通过DOM方法setInterval(code,time)方法来实现实时的刷新。
- 简单一个Html页面
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">3: <head>4: <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />5: <link rel="stylesheet" href="css/clock.css" />6: <title>简单时钟</title>7: </head>8: <body>9: <div id="clock">10: <div class="year">11: <div id="Year" class="num">0000</div>12: <div id="year">年</div>13: <div id="Month" class="num">00</div>14: <div id="month">月</div>15: <div id="Date" class="num">00</div>16: <div id="date">日</div>17: </div>18: <div class="time">19: <div id="Hour" class="num">00</div>20: <div class="sign">:</div>21: <div id="Minute" class="num">00</div>22: <div class="sign">:</div>23: <div id="Second" class="num">00</div>24: <div id="week">星期</div>25: <div id="Week" class="num">一</div>26: </div>27: </div>28: </body>29: </html>
2. clock.js的实现
1: var timer=null;2: var aNow=null;3: var g_oImgWeek=null;4: var aWeekName=["日", "一", "二", "三","四", "五", "六"];5:
6: function setclock()7: {
8: setInterval(checkSwitch, 1000);
9: };
10: function checkSwitch()11: {
12: var year=document.getElementById('Year');13: var month=document.getElementById('Month');14: var date=document.getElementById('Date');15: var hour=document.getElementById('Hour');16: var minute=document.getElementById('Minute');17: var second=document.getElementById('Second');18: var week=document.getElementById('Week');19:
20: aNow=getTimeArray();
21:
22: year.innerHTML=aNow[0];
23: month.innerHTML=aNow[1];
24: date.innerHTML=aNow[2];
25: hour.innerHTML=aNow[3];
26: if(aNow[4] < 10){27: minute.innerHTML='0'+aNow[4];28: }
29: else{30: minute.innerHTML=aNow[4];
31: }
32: if(aNow[5] < 10){33: second.innerHTML='0'+aNow[5];34: }
35: else{36: second.innerHTML=aNow[5];
37: }
38: week.innerHTML=aWeekName[aNow[6]];
39:
40: }
41:
42: function toDouble(iNum)43: {
44: if(iNum<10)45: {
46: return ' 0'+iNum;47: }
48: else49: {
50: return ' '+iNum;51: }
52: }
53:
54: function getTimeArray()55: {
56: var oDate=new Date();57: var aNumber=[];58:
59: var iYear=oDate.getYear();60: var iMonth=oDate.getMonth();61: var iDay=oDate.getDate();62: var iHour=oDate.getHours();63: var iMin=oDate.getMinutes();64: var iSec=oDate.getSeconds();65: var iWeek=oDate.getDay();66:
67: if(iYear<1900)68: {
69: iYear+=1900;
70: }
71:
72: var str=(iYear)+toDouble(iMonth+1)+toDouble(iDay)+toDouble(iHour)+toDouble(iMin)+toDouble(iSec)+' '+iWeek;73: var aChar=str.split(' ');74:
75: for(i=0;i<aChar.length;i++)76: {
77: aNumber[i]=parseInt(aChar[i]);
78: }
79: return aNumber;80: }
3.Html中引入clock.js文件
1: <script type="text/javascript" src="js/clock.js"></script>2: <script type="text/javascript">3: window.onload = function(){4: setclock();
5: }
6: </script>
整个过程就这么简单。