美文网首页
js实现指定时间倒计时方法

js实现指定时间倒计时方法

作者: owlcity | 来源:发表于2022-12-11 10:37 被阅读0次
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
</head>

<body>
  <div class="count_box"></div>
  <script>
    window.onload = function () {
      countDown();
      function fillZero(i) {
        return i < 10 ? "0" + i : i + "";
      }
      function countDown() {
        let nowtime = new Date();
        let endtime = new Date("2021/12/09,23:59:59");//日期格式建议用斜杠
        let result = parseInt((endtime.getTime() - nowtime.getTime()) / 1000);
        let d = parseInt(result / (24 * 60 * 60))
        let h = parseInt(result / (60 * 60) % 24);
        let m = parseInt(result / 60 % 60);
        let s = parseInt(result % 60);
        d = fillZero(d)
        h = fillZero(h);
        m = fillZero(m);
        s = fillZero(s);
        if (parseInt(d) > 0) {
          document.querySelector(".count_box").innerHTML = `距离当前时间:  ${d}天 ${h} 时 ${m} 分 ${s} 秒`;
        } else {
          if (parseInt(h) > 0) {
            document.querySelector(".count_box").innerHTML = `距离当前时间:  ${h} 小时 ${m} 分 ${s} 秒`;
          } else {
            if (parseInt(m) > 0) {
              document.querySelector(".count_box").innerHTML = `距离当前时间:  ${m} 分 ${s} 秒`;
            } else {
              document.querySelector(".count_box").innerHTML = `距离当前时间:  ${s} 秒`;
            }
          }

        }

        if (result <= 0) {
          document.querySelector(".count_box").innerHTML = "倒计时结束";
          return;
        }
        setTimeout(countDown, 1000);
      }
    }
  </script>
</body>

</html>

相关文章

网友评论

      本文标题:js实现指定时间倒计时方法

      本文链接:https://www.haomeiwen.com/subject/mzlfqdtx.html