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>
相关推荐
小码哥_常2 分钟前
一文带你吃透Android BLE蓝牙开发全流程
前端
熊文豪3 分钟前
Java 入门指南
开发语言·python
小码哥_常8 分钟前
从“新老交锋”看Retrofit与Ktor
前端
小菜鸡桃蛋狗25 分钟前
C++——类和对象(上)
开发语言·c++
伯恩bourne29 分钟前
Google Guava:Java 核心工具库的卓越之选
java·开发语言·guava
小J听不清31 分钟前
CSS 外边距(margin)全解析:取值规则 + 实战用法
前端·javascript·css·html·css3
2401_8795034135 分钟前
C++中的观察者模式变体
开发语言·c++·算法
lsx2024061 小时前
Rust 迭代器
开发语言
还是大剑师兰特1 小时前
Stats.js 插件详解及示例(完全攻略)
前端·大剑师·stats
前端小超超1 小时前
Vue计算属性computed:可写与只读的区别
前端·javascript·vue.js