这里写图片描述
<!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>Document</title>
</head>
<body>
<h1 id="time"></h1> <!-- 倒计时显示的位置 -->
<script type="text/javascript">
window.onload =function () {
function timer() {
//计算相差多少毫秒 未来时间.需要传参.月份"month-1" 当前时间
var minusTime = (new Date(2017,11,31,23,0,0)) - (new Date());
//获取元素
var days = parseInt(minusTime / 86400000); //1天 = 86400000毫秒
var hours = parseInt((minusTime % 86400000) / 3600000);//1小时 = 3600000毫秒
var minutes = parseInt((minusTime % 3600000) / 60000);//1分钟 = 60000毫秒
var seconds = parseInt((minusTime % 60000) / 1000);//1秒 = 1000毫秒
//空位补零.
function checkTime(i) {//将0-9的数字前面加上0\. 1变为01
if (i < 10) {
return '0' + i;
}else {
return i;
}
}
//带入函数,获取新元素
days = checkTime(days);
hours = checkTime(hours);
minutes = checkTime(minutes);
seconds = checkTime(seconds);
//获取最终时间
document.getElementById('time').innerHTML = days + "天 " + hours + ":" + minutes + ":" + seconds;
}
timer();//立即调用这个函数。解决延时1sの问题
setInterval (timer,1000);//将以上所有函数带入'间隔性定时器(A,1000)'
}
</script>
</body>
</html>