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>
相关推荐
web打印社区3 小时前
网页静默打印热敏小票:从 HTML 到出纸的完整指南
前端·javascript·vue.js·electron·pdf·html
剪刀石头布啊4 小时前
设计一个多计时任务的任务管理功能
前端
ModyQyW5 小时前
vite-plugin-uni-manifest 更新了什么
前端·typescript·uni-app
Asize6 小时前
AI 协作开发新范式:我用 SDD 做了个排版 npm 包
前端·人工智能
kyriewen7 小时前
我把今年流传的前端 AI 面试题整理了一遍——4 类场景题+回答框架(附速查表)
前端·面试·程序员
计算机魔术师8 小时前
国产多模态模型正面硬刚Opus旗舰:差距从30%缩到3%
前端
风骏时光牛马8 小时前
程序员进阶:深度思考,解锁职场成长的底层逻辑
前端
IT_陈寒8 小时前
用了Proxy才发现以前的JavaScript白写了
前端·人工智能·后端
爱丶不疚9 小时前
Eval: Agent 说的 Eval 是什么?从单测、TDD 到 Sentry 聊起
前端·ai编程·vibecoding
求道於盲9 小时前
python中的类型标注
前端