功能:javascript
1.實時顯示距離目標年份剩餘時間,精確到秒html
2.支持輸入年份參數java
遇到的問題總結:chrome
1.window.setInterval(fn,s),其中fn參數須要使用""包裹,不然計時器只執行一次,不能實時顯示。ide
2.兩個日期相減,獲得的是毫秒數;須要轉換成須要的單位(天+小時+分鐘+秒)ui
效果圖:spa
源碼:3d
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 6 <title>Examples</title> 7 <meta name="description" content=""> 8 <meta name="keywords" content=""> 9 <link href="" rel="stylesheet"> 10 <style> 11 #t{ 12 font-size: 1.5em; 13 height:100px; 14 width:600px; 15 border:3px dotted #FFAACC; 16 line-height: 100px; 17 text-align:center; 18 border-radius: 30px; 19 } 20 .mid{ 21 position:absolute; 22 left:50%; 23 top:50%; 24 margin:-50px 0 0 -300px; 25 } 26 </style> 27 </head> 28 <body> 29 <div id="t" class="mid"></div> 30 <script type="text/javascript"> 31 function getDiffTime(y){ 32 var n = new Date("12/31/"+(y-1) +" 23:59:59"); 33 var c = new Date(); 34 var diff=n-c; 35 var d=diff/(24*60*60*1000); 36 var h=(d-Math.floor(d))*24; 37 var m=(h-Math.floor(h))*60; 38 var s=(m-Math.floor(m))*60; 39 var str = "距離"+y+"年,還剩餘"+Math.floor(d)+"天"+Math.floor(h)+"小時"+Math.floor(m)+"分鐘"+Math.floor(s)+"秒"; 40 var divt = document.getElementById("t"); 41 t.innerHTML=str; 42 } 43 window.onload=init(); 44 function init(){ 45 var auto =window.setInterval("getDiffTime(2016)",1000); 46 } 47 </script> 48 </body> 49 </html>