效果图:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body {
background-color: #ccc;
}
p {
margin: 100px auto;
width: 1000px;
height: 100px;
line-height: 100px;
text-align: center;
font-weight: 700;
font-size: 32px;
background-color: skyblue;
}
</style>
</head>
<body>
<div>
<p id="t"></p>
</div>
<script>
// 倒计时函数
function overDateTime(time) {
let nowTime = new Date();
let inputTime = new Date(time);
if (inputTime - nowTime > 0) {
let times = (inputTime - nowTime) / 1000;
let d = parseInt(times / 60 / 60 / 24);
d = d < 10 ? '0' + d : d;
let h = parseInt(times / 60 / 60 % 24);
h = h < 10 ? '0' + h : h;
let m = parseInt(times / 60 % 60);
m = m < 10 ? '0' + m : m;
let s = parseInt(times % 60);
s = s < 10 ? '0' + s : s;
console.log(d, h, m, s)
return d + '天' + h + '时' + m + '分' + s + '秒';
} else {
return '倒计时结束!';
}
}
// 设置终止时间
time = '2023-2-15 16:57:56';
// 设置定时器1秒运行1次
window.setInterval(function () {
let timeDay = overDateTime(time);
let pTime = document.getElementById('t');
pTime.innerHTML = timeDay;
}, 1000);
</script>
</body>
</html>