倒计时 原理:时间差 = 目标(未来)时间-当前时间
目标(未来)时间可以随时改变,代码里面有显示的备注。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.box{
width: 520px;
height: 80px;
border-bottom: 2px solid pink;
border-top: 2px solid pink;
text-align: center;
margin: 0 auto;
}
.box .hh{
width: 100%;
height: 30px;
background-color: teal;
line-height: 30px;
margin-top: 1px;
}
.box span{
display: inline-block;
width: 40px;
height: 40px;
background: #f5004b;
color: #ffffff;
font-size: 18px;
line-height: 40px;
margin-top: 5px;
margin-left: 5px;
}
</style>
<body>
<script>
daojishi()
setInterval(daojishi, 1000)
function daojishi() {
//1.获取当前时间
var currentTime = new Date();
//2.目标时间
var targetTime = new Date("2020,12,25,0:0:0");
//时间没到就一直执行,时间到了就显示else的内容。
if ((targetTime - currentTime) >= 0) {
//3.时间差 默认毫秒 /1000 变成秒,取整
var time = parseInt((targetTime - currentTime) / 1000);
/*
m = s/60
h = s/60/60
t = s/60/60/24 =s/86400
*/
var tian = parseInt(time / 86400);//天数
var shi = parseInt(time % 86400 / 3600);//小时数
var fen = parseInt(time % 3600 / 60);//分钟数
var miao = time % 60;//秒数
document.body.innerHTML = "<div class='box'>"+"<div class='hh'>距离平安夜:</div>" +"<span>" +fillZero(tian)+"</span>" + "天" + "<span>" +fillZero(shi) +"</span>"+ ":" +"<span>"+ fillZero(fen)+"</span>" + ":" + "<span>"+fillZero(miao)+"</span>" +"</div>";
}else{
document.body.innerHTML = "<div class='box'>"+"<div class='hh'>距离平安夜:</div>" +"<span>" +00+"</span>" + "天" + "<span>" + 00 +"</span>"+ ":" +"<span>"+ 00+"</span>" + ":" + "<span>"+00+"</span>" +"</div>";
alert("圣诞快乐");
}
}
function fillZero(num) {
return num < 10 ? "0" + num : num
}
</script>
</body>
</html>