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守墓人35 分钟前
【前端】ikun-markdown: 纯js实现markdown到富文本html的转换库
前端·javascript·html
序属秋秋秋39 分钟前
《C++初阶之内存管理》【内存分布 + operator new/delete + 定位new】
开发语言·c++·笔记·学习
Savior`L41 分钟前
CSS知识复习5
前端·css
许白掰41 分钟前
Linux入门篇学习——Linux 工具之 make 工具和 makefile 文件
linux·运维·服务器·前端·学习·编辑器
ruan1145142 小时前
MySQL4种隔离级别
java·开发语言·mysql
quant_19863 小时前
R语言如何接入实时行情接口
开发语言·经验分享·笔记·python·websocket·金融·r语言
中微子5 小时前
🔥 React Context 面试必考!从源码到实战的完整攻略 | 99%的人都不知道的性能陷阱
前端·react.js
中微子6 小时前
React 状态管理 源码深度解析
前端·react.js
百锦再7 小时前
详细解析 .NET 依赖注入的三种生命周期模式
java·开发语言·.net·di·注入·模式·依赖
风吹落叶花飘荡7 小时前
2025 Next.js项目提前编译并在服务器
服务器·开发语言·javascript