一、核心算法:
1、获取当前时间 startTtime
2、设置将来时间 endTime
3、因为我们当前的时间每一秒都会发生改变,因此我们只要利用 endTime-startTtime就能实现倒计时的效果,
4、+new Date() 可获取当前时间的毫秒数
5、+new Date('2021-07-19 09:09:00') 可设置时间
二、实现代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
ul {
display: flex;
justify-content: space-between;
width: 200px;
margin: 100px auto;
}
ul li {
display: flex;
justify-content: center;
align-items: center;
list-style-type: none;
margin-left: 5px;
width: 50px;
height: 50px;
background-color: black;
color: #fff;
font-size: 20px;
}
img {
position: absolute;
}
</style>
</head>
<body>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
<img src="./img/angel.gif" alt="">
<script>
// 倒计时
var ul = document.querySelector('ul');
var endtime = +new Date('2021-07-18 15:02:00');
getTime();
// 开启定时器
setInterval(getTime, 1000);
function getTime() {
var nowtime = +new Date(); // 获取当前时间的毫秒数
var time = (endtime - nowtime) / 1000; // 剩余时间的秒数
var h = parseInt(time / 60 / 60 % 24); // 时
h = h < 10 ? '0' + h : h;
ul.children[0].innerHTML = h;
var m = parseInt(time / 60 % 60); // 分
m = m < 10 ? '0' + m : m;
ul.children[1].innerHTML = m;
var s = parseInt(time % 60); // 秒
s = s < 10 ? '0' + s : s;
ul.children[2].innerHTML = s;
}
</script>
</body>
</html>
三、实现效果