温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

js如何实现秒表计时器

发布时间:2021-04-19 11:00:27 来源:亿速云 阅读:209 作者:小新 栏目:web开发

这篇文章将为大家详细讲解有关js如何实现秒表计时器,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

秒表计时器的实现:

效果图如下:

js如何实现秒表计时器

附代码,已调试运行

<!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>
  #div1 {
   width: 300px;
   height: 400px;
   background: skyblue;
   margin: 100px auto;
   text-align: center;
  }
  
  #count {
   width: 200px;
   height: 150px;
   line-height: 150px;
   margin: auto;
   font-size: 40px;
  }
  
  #div1 input {
   width: 150px;
   height: 40px;
   background: orange;
   font-size: 25px;
   margin-top: 20px
  }
 </style>
</head>

<body>
 <div id="div1">
  <div id="count">
   <span id="id_H">00</span>
   <span id="id_M">00</span>
   <span id="id_S">00</span>
  </div>
  <input id="start" type="button" value="开始">
  <input id="pause" type="button" value="暂停">
  <input id="stop" type="button" value="停止">
 </div>
 <script>
  //可以将查找标签节点的操作进行简化 var btn = getElementById('btn')
  function $(id) {
   return document.getElementById(id)
  }
  window.onload = function() {
   //点击开始建 开始计数
   var count = 0
   var timer = null //timer变量记录定时器setInterval的返回值
   $("start").onclick = function() {
    timer = setInterval(function() {
     count++;
     console.log(count)
      // 需要改变页面上时分秒的值
     console.log($("id_S"))
     $("id_S").innerHTML = showNum(count % 60)
     $("id_M").innerHTML = showNum(parseInt(count / 60) % 60)
     $("id_H").innerHTML = showNum(parseInt(count / 60 / 60))
    }, 1000)
   }
   $("pause").onclick = function() {
     //取消定时器
     clearInterval(timer)
    }
    //停止记数 数据清零 页面展示数据清零
   $("stop").onclick = function() {
    //取消定时器
    $("pause").onclick()
     // clearInterval(timer)
     //数据清零 总秒数清零
    count = 0
     //页面展示数据清零
    $("id_S").innerHTML = "00"
    $("id_M").innerHTML = "00"
    $("id_H").innerHTML = "00"
   }

   //封装一个处理单位数字的函数
   function showNum(num) {
    if (num < 10) {
     return '0' + num
    }
    return num
   }
  }
 </script>
</body>

</html>

关于“js如何实现秒表计时器”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI