简单倒计时的实现HTML+CSS+JS

<!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>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值