计数时:
结束时:
示例:
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <meta http-equiv="X-UA-Compatible" content="ie=edge,chrome"> 8 <title>活动倒计时示例</title> 9 </head> 10 11 <body> 12 <div class="time"> 13 <span id="day">00</span> 14 <span id="hour">00</span> 15 <span id="month">00</span> 16 <span id="second">00</span> 17 </div> 18 <script type="text/javascript"> 19 (function () { 20 // 页面加载完 21 window.onload = function () { 22 countTime(); 23 } 24 // 小于9则添加前缀:01 2.... 25 function checkTime(_zero) { 26 return _zero > 9 ? _zero : '0' + _zero; 27 } 28 function countTime() { 29 30 // 截止时间. 年、月、日 时、分、秒 - 设置结束时间后 - 自动关闭计时器. 31 var dateStr = "2018/8/14 08:00:00"; 32 33 //获取当前时间 34 var date = new Date(); 35 var now = date.getTime(); 36 //设置截止时间 37 var endDate = new Date(dateStr); 38 var end = endDate.getTime(); 39 //时间差 40 var leftTime = end - now; 41 //定义变量 d,h,m,s保存倒计时的时间 42 var d, h, m, s; 43 if (leftTime >= 0) { 44 // 计天、时、分、秒 45 d = Math.floor(leftTime / 1000 / 60 / 60 / 24); 46 h = Math.floor(leftTime / 1000 / 60 / 60 % 24); 47 m = Math.floor(leftTime / 1000 / 60 % 60); 48 s = Math.floor(leftTime / 1000 % 60); 49 //将倒计时赋值到div中 50 document.getElementById("day").innerHTML = d > 9 ? d + '天' : checkTime(d) + "天"; 51 document.getElementById("hour").innerHTML = h > 9 ? h + '时' : checkTime(h) + "时"; 52 document.getElementById("month").innerHTML = m > 9 ? m + '分' : checkTime(m) + "分"; 53 document.getElementById("second").innerHTML = s > 9 ? s + '秒' : checkTime(s) + "秒"; 54 //递归每秒调用countTime方法,显示动态时间效果 55 setTimeout(countTime, 1000); 56 } else { 57 document.getElementById("day").innerHTML = "00天"; 58 document.getElementById("hour").innerHTML = "00时"; 59 document.getElementById("month").innerHTML = "00分"; 60 document.getElementById("second").innerHTML = "00秒"; 61 } 62 } 63 })(); 64 65 </script> 66 </body> 67 68 69 </html>