JavaScript实现计时器

用JavaScript实现了一个简单的计时器,通过按钮控制,实现了计时器的“开始计时”、“暂停计时”、“复位”功能。

样式较为简陋,后期会继续修改,并完善功能。

因为代码较少,就放在一个文件中了。

在火狐浏览器中的效果如图:

运行HTML文件后,未点击按钮:

点击开始按钮后:

做的过程中遇到的问题:

原计划是通过修改类名,把“开始计时”和“暂停计时”两个按钮合并为一个的,但是因为分两个按钮做的效果更好且更容易实现,所以还是用来两个button类型的<input>标签。

jishi.html

<!--Created by real_pbyyy on 2017/3/18.-->
<!
DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>TimeCount</title> <style> #pause{ display: none; } .count{ width:300px; height:150px; background: whitesmoke; border:solid darkgray 1px; border-radius: 1px; padding:20px; margin:0 auto; margin-top:60px; } p{ margin:30px; } </style> </head> <body> <div class="count"> <p id="tCount"></p> <p id="tCount2"></p> <input type="button" value="开始计时" id="start"/> <input type="button" value="暂停计时" id="pause" /> <input type="button" value="复位" id="reset"/> </div> <script> //tCount2是准备实现倒计时功能的,现在还没做 var tCount = document.getElementById("tCount"), tCount2 = document.getElementById("tCount2"), sBtn =document.getElementById("start"), rBtn = document.getElementById("reset"), pBtn = document.getElementById("pause"), txt = document.createTextNode("00:00:00"), t=1, s; tCount.appendChild(txt); //按钮事件 function control() { sBtn.onclick=function () { sBtn.style.display = "none"; pBtn.style.display = "inline"; count(); }; rBtn.onclick=function(){ reset(); sBtn.style.display="inline"; pBtn.style.display="none"; } pBtn.onclick=function () { sBtn.style.display="inline"; pBtn.style.display="none"; pause(); } } //计算时间 function timeAdd() { if(t<10){ txt.nodeValue = "00:00:0"+t; }else if(t>=10&&t<60){ txt.nodeValue = "00:00:"+t; }else if(t<3600&&t>60){ var m = Math.floor(t/60); var t1 = t%60; if(m<10){ if(t1<10){ txt.nodeValue = "00:0"+m+":0"+t1; }else if(t1>=10&&t1<60){ txt.nodeValue = "00:0"+m+":"+t1; } }else if(m<60&&m>=10){ if(t1<10){ txt.nodeValue = "00:"+m+":0"+t1; }else if(t1>=10&&t1<60){ txt.nodeValue = "00:"+m+":"+t1; } } }else if(t>=3600){ var h = Math.floor(t/3600); var m = Math.floor((t-3600*h)/60); var t1 = t%60; var mt; if(m<10){ if(t1<10){ mt = "0"+m+":0"+t1; }else if(t1>=10&&t1<60){ mt = "0"+m+":"+t1; } }else if(m<60&&m>=10){ if(t1<10){ mt = m+":0"+t1; }else if(t1>=10&&t1<60){ mt = m+":"+t1; } } txt.nodeValue = h+":"+ mt; } t++; } //刷新时间显示 function count(){ s = setInterval("timeAdd()",1000); } //复位键的功能实现 function reset() { clearInterval(s); txt.nodeValue = "00:00:00"; t = 1; s = null; } //暂停键的功能实现 function pause() { var now = txt.nodeValue; clearInterval(s); } window.onload=function () { control(); } </script> </body> </html>

2017.3.18

转载于:https://www.cnblogs.com/bingyupan/p/6569355.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值