实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>春节倒计时</title> <style> body{text-align: center} .time{ width: 800px; height: 300px; background-color: coral; margin: 0 auto; margin-top: 20px; } p{ padding: 50px; } </style> </head> <body> <div class="time"> <p style="color: cornsilk">2019年农历春节倒计时:还剩<span></span></p> </div> <script> var oSpan = document.getElementsByTagName('span')[0]; function tow(n) { return n >= 0 && n < 10 ? '0' + n : '' + n; } function getDate() { var oDate = new Date();//获取日期对象 var oldTime = oDate.getTime();//现在距离1970年的毫秒数 var newDate = new Date('2019/2/5 00:00:00'); var newTime = newDate.getTime();//2019年春节距离1970年的毫秒数 var second = Math.floor((newTime - oldTime) / 1000);//未来时间距离现在的秒数 var day = Math.floor(second / 86400);//整数部分代表的是天;一天有24*60*60=86400秒 ; second = second % 86400;//余数代表剩下的秒数; var hour = Math.floor(second / 3600);//整数部分代表小时; second %= 3600; //余数代表 剩下的秒数; var minute = Math.floor(second / 60); second %= 60; var str = tow(day) + '<span class="time">天</span>' + tow(hour) + '<span class="time">小时</span>' + tow(minute) + '<span class="time">分钟</span>' + tow(second) + '<span class="time">秒</span>'; oSpan.innerHTML = str; } getDate(); setInterval(getDate, 1000); </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例