Before doing the countdown, let me talk about a method setInterval(). This method can call a function repeatedly, so the countdown effect can be achieved with this method
1.要做倒计时,首先是要获取当前时间,要知道最终时间是什么时候才可以倒计时
2.用最终时间减去当前时间,可以知道还剩下多少时间到达目标时间
3.用数学方法就可以得知倒计时的时分秒(具体看代码)
4.要注意的是,因为setInterval()是在一秒后才会触发,所以一开始的时间并不是倒计时时间,所以可以将setInterval()这个方法先调用一次.
实现效果如下
code show as below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.hour{
height: 40px;
width: 40px;
background: black;
text-align: center;
color: white;
float: left;
margin-left: 2px;
}
.minute{
height: 40px;
width: 40px;
background: black;
text-align: center;
color: white;
float: left;
margin-left: 2px;
}
.second{
height: 40px;
width: 40px;
background: black;
text-align: center;
color: white;
float: left;
margin-left: 2px;
}
</style>
</head>
<body>
<div>
<span class="hour">1</span>
<span class="minute">2</span>
<span class="second">3</span>
</div>
<script>
var hours=document.querySelector('.hour');
var minutes=document.querySelector('.minute');
var seconds=document.querySelector('.second');
var inputTime=+new Date('2020-9-11 12:00:00');
countDate();
setInterval(countDate,1000);
function countDate(){
var nowTime=+new Date();
var times=(inputTime-nowTime)/1000;
var h =parseInt(times/60/60%24);
var m =parseInt(times/60%60);
var s =parseInt(times%60);
h=h<10 ?'0 '+h:h;
m=m<10 ?'0 '+m:m;
s=s<10 ?'0 '+s:s;
hours.innerHTML=h;
minutes.innerHTML=m;
seconds.innerHTML=s;
}
</script>
</body>
</html>