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>
相关推荐
精神小伙就是猛3 分钟前
C# sealed密封 追本溯源
开发语言·c#
真正的醒悟14 分钟前
图解网络35
开发语言·网络·php
大连好光景26 分钟前
批量匿名数据重识别(debug记录)
开发语言·python
计算机毕设VX:Fegn089526 分钟前
计算机毕业设计|基于Java + vue水果商城系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·课程设计
周杰伦_Jay27 分钟前
【 Vue前端技术详细解析】目录结构与数据传递
前端·javascript·vue.js
清水白石00833 分钟前
《深入 Celery:用 Python 构建高可用任务队列的实战指南》
开发语言·python
Tony Bai37 分钟前
Jepsen 报告震动 Go 社区:NATS JetStream 会丢失已确认写入
开发语言·后端·golang
无敌最俊朗@40 分钟前
STL-list面试剖析(面试复习4)
开发语言
bing.shao43 分钟前
Golang 之 defer 延迟函数
开发语言·后端·golang
无敌最俊朗@1 小时前
Qt 多线程编程: moveToThread 模式讲解
java·开发语言