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

posted on 2017-03-18 01:23  real_pbyyy  阅读(800)  评论(0编辑  收藏  举报

导航