溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

JS實現簡易計時器

發布時間:2020-02-28 00:20:57 來源:網絡 閱讀:273 作者:Cherish純紫 欄目:開發技術
<!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" />
    <style>
      .container {
        width: 300px;
        height: 100px;
        background-color: #eee;
        padding: 20px 10px;
        margin: 100px auto;
      }
      .box {
        width: 100px;
        height: 30px;
        margin: 30px auto;
      }
      .box span {
        color: red;
        font-size: 20px;
        display: inline-block;
        padding: 0 5px;
      }
    </style>
    <title>Document</title>
  </head>
  <body>
    <div class="container">
      <input type="number" id="time" />
      <button id="btn1">計時開始</button>
      <button id="btn2">暫停</button>
      <button id="btn3">結束</button>
      <div class="box">倒計時<span></span>秒</div>
    </div>
  </body>

  <script>
    var time = document.querySelector('#time')
    var btn1 = document.querySelector('#btn1')
    var btn2 = document.querySelector('#btn2')
    var btn3 = document.querySelector('#btn3')
    var span = document.querySelector('.box').children[0]
    // 計時
    btn1.addEventListener('click', function() {
      var val = time.value
      time.value = ''
      if (!val) {
        alert('請輸如大于0的時間,單位:秒')
      } else {
        var timeId = funTime(val)
      }

      // 暫停
      btn2.addEventListener('click', function() {
        var txt = btn2.innerHTML
        if (span.innerHTML) {
          if (txt == '暫停') {
            clearInterval(timeId)
            btn2.innerHTML = '開始'
          } else {
            timeId = funTime(span.innerHTML)
            btn2.innerHTML = '暫停'
          }
        }
      })

      // 結束
      btn3.addEventListener('click', function() {
        if (timeId) {
          clearInterval(timeId)
          span.innerHTML = ''
        }
      })

      // 計時器函數
      function funTime(val) {
        span.innerHTML = val
        var timer = setInterval(() => {
          if (val === 0) {
            clearInterval(timeId)
            span.innerHTML = ''
            alert('時間到!')
          } else {
            val--
            span.innerHTML = val
          }
        }, 1000)
        return timer
      }
    })
  </script>
</html>
向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女