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>
相关推荐
八股文领域大手子4 分钟前
Java死锁排查:线上救火实战指南
java·开发语言·面试
点云SLAM7 分钟前
Python中列表(list)知识详解(2)和注意事项以及应用示例
开发语言·人工智能·python·python学习·数据结果·list数据结果
国强_dev8 分钟前
任意复杂度的 JSON 数据转换为多个结构化的 Pandas DataFrame 表格
开发语言·python
GISer_Jing18 分钟前
React useState 的同步/异步行为及设计原理解析
前端·javascript·react.js
mini榴莲炸弹21 分钟前
什么是SparkONYarn模式?
前端·javascript·ajax
能来帮帮蒟蒻吗21 分钟前
VUE3 -综合实践(Mock+Axios+ElementPlus)
前端·javascript·vue.js·笔记·学习·ajax·typescript
酷爱码25 分钟前
HTML5中的Microdata与历史记录管理详解
前端·html
o(╥﹏╥)26 分钟前
绑定 SSH key(macos)
开发语言·git·学习·macos
小龙Guo37 分钟前
QT+opencv实现卡尺工具找圆、拟合圆
开发语言·qt·opencv
开开心心就好40 分钟前
高效全能PDF工具,支持OCR识别
java·前端·python·pdf·ocr·maven·jetty