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>
相关推荐
guslegend2 分钟前
AGENT.md,Skill与工程规范
java·开发语言·数据库
jingling5555 分钟前
Flutter | Dio网络请求实战
android·开发语言·前端·flutter
周末也要写八哥6 分钟前
C++中单线程方式之无脑上锁
java·开发语言·c++
向上的车轮8 分钟前
Next.js 入门指南:从零到一构建全栈应用
开发语言·javascript·ecmascript
freeinlife'11 分钟前
精准秒表计时器实现---基于js
开发语言·前端·javascript
東隅已逝,桑榆非晚14 分钟前
新手入门指南:认识 C 语言文件操作(上)
c语言·开发语言·笔记
cany100016 分钟前
C++ -- 动态内存分配和释放(new/delete)
开发语言·c++
王文?问21 分钟前
ESP32-S3 实战教程:本地语音识别控制 Web 塔防游戏,从固件到前端完整跑通
前端·游戏·语音识别
brycegao32126 分钟前
Vue3+Go 全栈项目上线阿里云|从 0 到 1 踩坑全纪录
开发语言·阿里云·golang
ch.ju28 分钟前
Java Programming Chapter 4——cite
java·开发语言