手写一个电商秒杀倒计时功能?安排!(原生)

500 阅读1分钟

1、需求分析

  • 进入页面 1 秒之后开始倒计时,也就是1000ms
  • s--
  • s<0 s=59 m--
  • m<0 m=59 h--
  • h 、 m、 s<100 (用三元表达式或封装补零函数)
  • 把数据赋值给 h m s
  • 如果 h==0&&m==0&&s==0 停止计时器,移除自身

2、代码落地

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Document</title>
  <style>
    span {
      display: inline-block;
      width: 80px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      background-color: red;
      color: #000;
      font-size: 30px;
    }

    strong {
      font-size: 30px;
    }
  </style>
</head>

<body>
  <div class="clock">
    <span id="hour">00</span>
    <strong>:</strong>
    <span id="minute">01</span>
    <strong>:</strong>
    <span id="second">10</span>
  </div>
  <script>
    let clock = document.querySelector('.clock')//获取倒计时的盒子
    let body = document.body //获取body
    // 进入页面开启1秒倒计时
    let timeID = setInterval(function () {
      let h = +document.querySelector('#hour').innerHTML
      let m = +document.querySelector('#minute').innerHTML
      let s = +document.querySelector('#second').innerHTML

      s--
      if (s < 0) {
        s = 59
        m--
      }

      if (m < 0) {
        m = 59
        h--
      }

      h = h < 10 ? '0' + h : h
      m = m < 10 ? '0' + m : m
      s = s < 10 ? '0' + s : s

      document.querySelector('#hour').innerHTML = h
      document.querySelector('#minute').innerHTML = m
      document.querySelector('#second').innerHTML = s

      if (h == 0 && m == 0 && s == 0) {
        // 1.清除定时器
        clearInterval(timeID)
        // 2.移除自身
        // 法1.时间一到,自己把自己删了
        // clock.remove(clock)
        // 法2.时间一到,body把自己的孩子给删除了
        // body.removeChild(clock)
        // 法2.时间一到,自己的妈妈把自己清除了
        // clock.parentNode.remove(clock)
        // 法4.时间一到,自己藏起来
        clock.style.display = 'none'
      }
    }, 1000)
  </script>
</body>

</html>