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>
相关推荐
80530单词突击赢9 分钟前
C++入门指南:从零到精通
开发语言·c++
小突突突10 分钟前
浅谈Java中的反射
java·开发语言
落霞的思绪11 分钟前
配置React和React-dom为CDN引入
前端·react.js·前端框架
Hacker_Z&Q12 分钟前
CSS 笔记2 (属性)
前端·css·笔记
csbysj202013 分钟前
JSP 发送邮件教程
开发语言
Anastasiozzzz20 分钟前
LeetCode Hot100 295. 数据流的中位数 MedianFinder
java·服务器·前端
Tansmjs32 分钟前
C++编译期数据结构
开发语言·c++·算法
金枪不摆鳍33 分钟前
算法-字典树
开发语言·算法
diediedei39 分钟前
C++类型推导(auto/decltype)
开发语言·c++·算法
索荣荣42 分钟前
Java动态代理实战:从原理到精通
java·开发语言