html实现倒计时

参考网址

html 复制代码
<!DOCTYPE html>
<html>
<head>
  <title>倒计时示例</title>
</head>
<body>
  <h1 id="titleCountDown"></h1>
  <div id="countdown"></div>

  <script>
    // 目标日期
    var targetDate = new Date("2024-10-11T15:40:00");
    const year = targetDate.getFullYear();
    const month = targetDate.getMonth() + 1;
    const day = targetDate.getDate();
    const hours = targetDate.getHours();
    const minutes = targetDate.getMinutes();
    const seconds = targetDate.getSeconds();
    document.getElementById("titleCountDown").innerHTML = `距离${year}-${month}-${day} ${hours}:${minutes}:${seconds}还有:`

    var timer = null;
    // 更新倒计时
    function updateCountdown() {
      var now = new Date();
      var timeLeft = targetDate - now;
      if (timeLeft < 0) {
        document.getElementById("countdown").innerHTML = "时间已过";
        return;
      }

      // 计算剩余的天、小时、分钟和秒
      var days = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
      var hours = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      var minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);

      // 更新页面上的倒计时显示
      document.getElementById("countdown").innerHTML = days + "天 " + hours + "小时 " + minutes + "分钟 " + seconds + "秒";

      // 每秒钟更新一次倒计时
      timer && clearTimeout(timer);
      timer = setTimeout(updateCountdown, 1000);
    }

    // 启动倒计时
    updateCountdown();
  </script>
</body>
</html>
相关推荐
wordbaby几秒前
🚀 从零到一实战:基于 Taro 构建纯血鸿蒙 (HarmonyOS NEXT) 应用踩坑全指南
前端
代龙涛1 分钟前
wordpress块主题
开发语言·后端·php
慧一居士3 分钟前
ESM 在前端开发中的介绍和使用指导
前端
禾味7 分钟前
过程即奖励|前端转后端经验分享
前端·后端·面试
苡~17 分钟前
【openclaw+claude】手机+OpenClaw+Claude实现远程AI编程系列大纲
java·前端·人工智能·智能手机·ai编程·claude api
毕设源码-赖学姐25 分钟前
【开题答辩全过程】以 基于java电脑售后服务管理系统设计为例,包含答辩的问题和答案
java·开发语言
Ryan今天学习了吗34 分钟前
前端知识体系总结-前端工程化(Webpack篇)
前端·面试·前端工程化
Ryan今天学习了吗35 分钟前
前端知识体系总结-前端工程化(Babel篇)
前端·面试·前端工程化
GISer_Jing36 分钟前
基于 OpenClaw 构建 博客自动撰写 Agent
前端·aigc·ai写作
潜水豆39 分钟前
基于cursor 的自用专家系统v0.2
前端