1 <body> 2 <!-- 页面放个盒子,显示时间 --> 3 <div id="box" style="font-size: 50px; text-align: center;"></div> 4 </body>
1 <script> 2 // 创建补零函数 3 function creatZero(n){ 4 if(n<10){ 5 return "0"+n; 6 } 7 return n; 8 } 9 // 创建格式化日期函数 10 function getDate(){ 11 var obj = new Date(); 12 var year = obj.getFullYear(); 13 var month = obj.getMonth()+1; 14 var date = obj.getDate(); 15 var day = obj.getDay(); 16 var hour= obj.getHours(); 17 var minute = obj.getMinutes(); 18 var second = obj.getSeconds(); 19 var mSecond = obj.getMilliseconds(); 20 switch(day){ 21 case 0 :day = "日";break; 22 case 1 :day = "一";break; 23 case 2 :day = "二";break; 24 case 3 :day = "三";break; 25 case 4 :day = "四";break; 26 case 5 :day = "五";break; 27 case 6 :day = "六";break; 28 } 29 return { 30 year:year, 31 month:creatZero(month), 32 date:creatZero(date), 33 day:day, 34 hour:creatZero(hour), 35 minute:creatZero(minute), 36 second:creatZero(second), 37 mSecond:mSecond 38 } 39 } 40 // 获取页面的盒子 41 var timeBox = document.getElementById("box"); 42 // 计时器初始会等待一秒之后执行,所以刷新页面会有一秒空白,计时器前先执行一次可解决 43 // 然后将代码交给计时器执行即可 44 var d = getDate(); 45 timeBox.innerHTML = d.year +"年"+ d.month +"月"+ d.date +"日星期"+ d.day + 46 " "+ d.hour +":" + d.minute +":"+ d.second; 47 // 利用计时器,每隔一秒,获取并拼接一次 48 setInterval(function(){ 49 var d = getDate(); 50 box.innerHTML = d.year +"年"+ d.month +"月"+ d.date +"日星期"+ d.day + 51 " "+ d.hour +":" + d.minute +":"+ d.second; 52 }, 1000); 53 </script>