这是一个简单的小案例,本案例用到的知识点有:
- 时间内置对象
- js定时器这个方法
- 对时间进行补0操作
效果:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=di, initial-scale=1.0">
<title>Document</title>
<style>
.father {
position: relative;
height: 200px;
width: 200px;
background-color: chocolate;
}
.one {
position: absolute;
width: 200px;
height: 60px;
top: 30px;
left: 0;
text-align: center;
line-height: 50px;
color: white;
font-size: 30px;
}
.mintues {
float: left;
width: 50px;
height: 50px;
background-color: black;
margin-right: 20px;
margin-top: 140px;
text-align: center;
line-height: 50px;
color: white;
font-size: 30px;
}
.second {
float: left;
width: 50px;
height: 50px;
background-color: black;
margin-top: 140px;
text-align: center;
line-height: 50px;
color: white;
font-size: 30px;
}
.hour {
float: left;
width: 50px;
height: 50px;
background-color: black;
margin-top: 140px;
text-align: center;
line-height: 50px;
color: white;
font-size: 30px;
margin-right: 20px;
}
</style>
</head>
<body>
<div class="father">
<div class="one">倒计时</div>
<div class="hour">1</div>
<div class="mintues">2</div>
<div class="second">3</div>
</div>
<script>
var hour=document.querySelector('.hour');
var mintues=document.querySelector('.mintues');
var second=document.querySelector('.second');
var inputTime = +new Date('2021-10-23 00:00:00'); //返回用户输入的毫秒数
countDown();//先调用一次直接改变内容
function countDown() {
var nowTime = +new Date();//返回当前毫秒数
var times = (inputTime - nowTime) / 1000;//两者相减的时间戳总秒数 1s=1000ms
var h=parseInt(times/60/60%24);
h=h<10? '0'+h:h;
hour.innerHTML=h;
var m=parseInt(times/60%60);
m=m<10? '0'+m:m;
mintues.innerHTML=m;
var s=parseInt(times%60);
s=s<10? '0'+s:s;
second.innerHTML=s;
}
setInterval(countDown,1000);
</script>
</body>
</html>