js秒表计时器

js秒表计时器

用普通js实现秒表计时器

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>计时器</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      #box {
        margin: 50px auto;
        width: 300px;
        height: 400px;
        background-color: aquamarine;
      }
      .content {
        height: 100px;
        text-align: center;
        line-height: 100px;
        font-weight: 700;
        font-size: 40px;
      }
      .btn {
        text-align: center;
      }
      button {
        margin-top: 20px;
        font-size: 50px;
      }
    </style>
  </head>
  <body>
    <div id="box">
      <div class="content">
        <span id="hours">00</span>
        <span id="minutes">00</span>
        <span id="seconds">00</span>
      </div>
      <div class="btn">
        <button id="start">开始计时</button>
        <button id="pause">暂停计时</button>
        <button id="end">结束计时</button>
      </div>
    </div>
  </body>
  <script>
    var timer
    var time = 0
    function $(id) {
      return document.getElementById(id)
    }
    var hours = $('hours'),
      minutes = $('minutes'),
      seconds = $('seconds'),
      start = $('start'),
      pause = $('pause'),
      end = $('end')
    //开始计时
    start.onclick = function () {
      this.disabled = true
      pause.disabled = false
      end.disabled = false
      timer = setInterval(move, 1000)
    }
    //暂停计时
    pause.onclick = function () {
      this.disabled = true
      start.disabled = false
      end.disabled = false
      clearInterval(timer)
    }
    //结束计时
    end.onclick = function () {
      this.disabled = true
      pause.disabled = false
      start.disabled = false
      clearInterval(timer)
      time = 0
      timeShow()
    }
    function move() {
      time++
      // console.log(time)
      timeShow()
    }
    function timeFormat(t) {
      t = t >= 10 ? t : '0' + t
      return t
    }
    function timeShow() {
      seconds.innerText = timeFormat(time % 60) //0-59
      minutes.innerHTML = timeFormat(parseInt(time / 60) % 60)
      hours.innerHTML = timeFormat(parseInt(time / 60 / 60) % 24)
    }
  </script>
</html>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值