<!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>
* {
margin: 0;
padding: 0;
}
.countdowm {
overflow: hidden;
margin: 50px auto;
width: 500px;
height: 300px;
background-color: aqua;
color: #fff;
text-align: center;
font-size: 24px;
}
.countdowm h3 {
margin-top: 50px;
font-size: 36px;
}
.countdowm h5 {
margin: 20px 0;
font-size: 28px;
color: #000;
}
.countdowm span {
font-size: 24px;
}
</style>
</head>
<body>
<div class="countdowm">
<h3>倒计时效果</h3>
<h5>距离2023年还剩</h5>
<span class="days"></span>天
<span class="hou"></span>时
<span class="min"></span>分
<span class="sec"></span>秒
</div>
<script>
var days = document.querySelector('.days')
var hou = document.querySelector('.hou')
var min = document.querySelector('.min')
var sec = document.querySelector('.sec')
// 获取总时间毫秒数
var totalTime = +new Date('2023-1-1 00:00:00')
// 先调用一次函数 确保页面一加载就开始进行倒计时
countTime();
setInterval(countTime, 1000)
function countTime(time) {
// 获取当前时间毫秒数
var nowTime = +new Date();
// 获取倒计时总秒数
var timer = (totalTime - nowTime) / 1000;
// 获取剩余年份
var dd = parseInt(timer / 60 / 60 / 24);
dd = dd < 10 ? '0' + dd : dd;
days.innerHTML = dd;
var hh = parseInt(timer / 60 / 60 % 24);
hh = hh < 10 ? '0' + hh : hh;
hou.innerHTML = hh;
var mm = parseInt(timer / 60 % 60);
mm = mm < 10 ? '0' + mm : mm
min.innerHTML = mm;
var ss = parseInt(timer % 60);
ss = ss < 10 ? '0' + ss : ss;
sec.innerHTML = ss;
}
</script>
</body>
</html>
![](https://i-blog.csdnimg.cn/blog_migrate/708e811ef1beef24998a167abc75a8e5.png)