当前位置: 移动技术网 > IT编程>开发语言>JavaScript > js实现简单的秒表

js实现简单的秒表

2020年03月09日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了js实现简单的秒表具体代码,供大家参考,具体内容如下

描述:

实现一个简单的秒表,点击启动按钮时开始计时,随后启动按钮变为暂停,

点击暂停暂停计时,点击复位回到最初始状态。

效果:

代码:

<!doctype html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>title</title>
 <style>
 #showtime
 {
  width: 300px;
  height: 60px;
  font-size: 60px;
  line-height: 60px;
 }
 </style>
</head>
<body>
 <div>
 <div id="showtime">00:00:00</div>
 <button id="startbn">启动</button>
 <button id="restbn">复位</button>
 </div>
<script>
 //——————
 var time,showtime,startbn,restbn,pausedate;
 //布尔开关
 var bool=false;
 //暂停的累计时间
 var pausetime=0;
 
 init();
 function init() {
 showtime=document.getelementbyid("showtime");
 startbn=document.getelementbyid("startbn");
 restbn=document.getelementbyid("restbn");
 startbn.addeventlistener("click",clickhandler);//开始按钮 ~ 暂停按钮
 restbn.addeventlistener("click",clickhandler);//复位按钮
 setinterval(animation,16);
 }
 
 //转化时间函数
 function animation() {
 if(!bool) return;
 //前时间减去上次开启时间减去暂停累计时间
 var times=new date().gettime()-time-pausetime;
 var minutes=math.floor(times/60000);//毫秒转化为分钟
 var seconds=math.floor((times-minutes*60000)/1000);//已知分钟 
 将time减去分钟 除去1000得出 秒
 var ms=math.floor((times-minutes*60000-seconds*1000)/10);//
 showtime.innerhtml=
  (minutes<10 ? "0" +minutes : minutes)+":"
  +(seconds<10 ? "0"+seconds :seconds)+":"
 +(ms<10 ? "0"+ms : ms);
 }
 
 //点击时的事件
 function clickhandler(e) {
 e= e || window.event;
 if(this===startbn){
  bool=!bool;
  if(bool){
  this.innerhtml="暂停";
  //如果我们上一次暂停时间是空,表示没有暂停过,因此,直接返回0
  //如果上次的暂停时间是有值得,用当前毫秒数减去上次的毫秒数,这样就会得到暂停时间
  pausetime+=(!pausedate ? 0 : new date().gettime()-pausedate);
  if(time) return;
  time=new date().gettime();
  return;//是为bool判断跳出
  }
 
  this.innerhtml="启动";
  pausedate=new date().gettime();
  return;//是为this是否等于startbn判断跳出
 }
 startbn.innerhtml="启动";
 pausetime=0;
 pausedate=null;
 bool=false;
 time=0;
 showtime.innerhtml="00:00:00";
 }
 
</script>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网