独书先生 Menu

Viewing all items for tag 倒计时

js倒计时自定义小时分钟

需求

实现一个倒计时一小时的网页应用

代码







Document

小时
分钟
<p class="count"></p>

<button id="start">START</button>
<script>
  window.onload = function () {
    // countDown();

    document.querySelector("#start").addEventListener("click", () => {
      function addZero(i) {
        return i < 10 ? "0" + i : i + "";
      }

      var hour = document.querySelector("#hour");
      var min = document.querySelector("#min");
      var countTimeHour = parseInt(hour.value === "" ? "1" : hour.value);
      var countTimeMin = parseInt(min.value === "" ? "0" : min.value);

      var nowtime = new Date(); //你已知的时间
      var t_s = nowtime.getTime(); //转化为时间戳毫秒数
      var endtime = new Date(); //定义一个新时间
      t_s = t_s + 1000 * 60 * countTimeMin; //设置新时间比旧时间多一分钟
      t_s = t_s + 1000 * 60 * 60 * countTimeHour; //设置新时间比旧时间多一小时;
      endtime.setTime(t_s);
      // nt.setTime(t_s+1000*60*60*24);//设置新时间比旧时间多一天

      countDown();

      function countDown() {
        var nowtime = new Date(); //你已知的时间
        //   var endtime = new Date("2019/03/16,17:57:00");
        var lefttime = parseInt(
          (endtime.getTime() - nowtime.getTime()) / 1000
        );
        var d = parseInt(lefttime / (24 * 60 * 60));
        var h = parseInt((lefttime / (60 * 60)) % 24);
        var m = parseInt((lefttime / 60) % 60);
        var s = parseInt(lefttime % 60);
        d = addZero(d);
        h = addZero(h);
        m = addZero(m);
        s = addZero(s);
        document.querySelector(
          ".count"
        ).innerHTML = `活动倒计时  ${d}天 ${h} 时 ${m} 分 ${s} 秒`;
        if (lefttime <= 0) {
          document.querySelector(".count").innerHTML = "Time Over!";
          var isShow = false;
          setInterval(() => {
            isShow = !isShow;
            if (isShow) {
              document.title = "😆Time Over!";
            } else {
              document.title = "";
            }
          }, 1000);
          return;
        }
        setTimeout(countDown, 1000);
      }
    });
    // window.countDown = function () {

    // };
  };
</script>



HTML倒计时效果:天、时、分、秒 | 固定时间倒计时

需求分析:

希望制作一个固定时间倒计时效果,比如某某活动在4小时之后结束,点开网页,触发倒计时事件,开始4小时倒计时。考虑使用setInterval定时器,在时间为0后,clearInterval清除定时器。

代码实例:

写一个span用于显示,记得引用jQuery Continue reading…