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>
相关推荐
Apifox3 分钟前
测试数据终于不用到处复制了,Apifox 自动化测试新增「共用测试数据」
前端·后端·测试
小小小小宇19 分钟前
Mac龙虾保姆级完整部署指南
前端
睡不着的可乐25 分钟前
vue2 和 vue3自定义指令有什么区别,都是怎么实现和使用一个指令
前端·vue.js
闲来没事抠鼻屎26 分钟前
Web打印插件实战:轻量化JS打印方案vue-print-designer落地指南
前端
孙凯亮29 分钟前
从 SSR 踩坑到 CSR 封神:Nuxt4 全流程终极实战
前端
想努力找到前端实习的呆呆鸟31 分钟前
网易云桌面端--精选歌单布局思路记录
前端·javascript·vue.js
Flywith2435 分钟前
【每日一技】Raycast 实现 scrcpy 的快捷显示隐藏
android·前端
薛端阳1 小时前
OpenClaw的架构优化思路杂想
前端
hi大雄1 小时前
我的 2025 — 名为《开始的勇气》🌱
前端·年终总结
OpenTiny社区1 小时前
TinyRobot:基于 OpenTiny Design 的企业级 AI 交互组件框架
前端·vue.js·ai编程