练习放假倒计时,理解date及定时器的使用。
点击查看代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
#time{
font-size: 40px;
color: red;
text-align: center;
}
</style>
</head>
<body>
<div id="time"></div>
<script>
window.onload = function () {
// 1.获取需要的标签
var time = document.getElementById('time');
// 2. 自定义将来的时间
var nextDate = new Date('2028/07/01 12:00:00');
// 3. 获取现在的时间
var currentDate = new Date();
// 4. 获取时间戳
var currentTime = currentDate.getTime();
var nextTime = nextDate.getTime();
// 5. 剩下的时间戳
var allTime = nextTime - currentTime;
// 6. 把毫秒转成秒
var allSecond = parseInt(allTime / 1000);
var d, h, m, s ;
// 7. 开启定时器
timer = setInterval(function () {
allSecond -=1;
// 8.转化
d = size(parseInt(allSecond / 3600 / 24));
h = size(parseInt(allSecond / 3600 % 24));
m = size(parseInt(allSecond / 60 % 60));
s = size(parseInt(allSecond % 60));
// 9. 注入
time.innerText = "距离放假还有"+ d +"天"+ h +"小时" + m +"分钟"+ s +"秒";
// 10.倒计时完成清除计时器
if (allSecond <= 0){
clearInterval(timer);
}
}, 1000);
function size(num) {
return num >= 10 ? num : '0' + num;
}
}
</script>
</body>
</html>