<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>倒计时效果</title>
</head>
<style>
.countdown {
display: flex;
justify-content: center;
align-items: center;
height: 100vh; /* 示例:占满整个视口高度 */
font-size: 24px;
font-weight: bold;
color: #fff;
background-color: #333;
}
.countdown-time span {
margin: 0 5px;
}
</style>
<body>
<div class="countdown">
<div class="countdown-time">
<span class="hour">00</span>:<span class="minute">00</span>:<span class="second">00</span>
</div>
</div>
<script>
// 假设目标时间为2024年8月25日12:00:00
var targetTime = new Date("2024-08-27T12:00:00").getTime();
function updateCountdown() {
var now = new Date().getTime();
var distance = targetTime - now;
// 如果倒计时结束,则停止更新
if (distance < 0) {
clearInterval(timer);
document.querySelector('.countdown-time').textContent = '活动已结束';
return;
}
// 计算天、小时、分钟和秒
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// 由于我们只需要小时、分钟和秒,因此不需要天
// 更新页面上的时间显示
document.querySelector('.hour').textContent = hours < 10 ? '0' + hours : hours;
document.querySelector('.minute').textContent = minutes < 10 ? '0' + minutes : minutes;
document.querySelector('.second').textContent = seconds < 10 ? '0' + seconds : seconds;
}
// 初始化倒计时并设置定时器
updateCountdown();
var timer = setInterval(updateCountdown, 1000);
</script>
</body>
</html>
01-04
02-06
7849
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-09
708
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)