本文實(shí)例為大家分享了js通過開始結(jié)束控制計(jì)時(shí)器的具體實(shí)現(xiàn)代碼,供大家參考,具體內(nèi)容如下
時(shí)間戳的使用的可以取消對多次點(diǎn)擊事件產(chǎn)生效果的累加,譬如下文,運(yùn)用時(shí)間戳,保證了在多次點(diǎn)擊事件后不會(huì)對setInterval()中的時(shí)間進(jìn)行疊加。
開始結(jié)束運(yùn)用addEventlistener()來控制開始結(jié)束,
實(shí)時(shí)顯示在你要顯示的文本內(nèi)容放置在setInterval()中,可實(shí)現(xiàn)實(shí)時(shí)顯示的效果。
不足setInterval()方法所設(shè)置的時(shí)間并不能保證一直是1秒的,有誤差,但是可通過前后Date()的不同控制在一定范圍內(nèi)才可執(zhí)行,不過這里暫時(shí)沒有設(shè)置這個(gè),有空再補(bǔ)。
<!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>簡單計(jì)時(shí)器</title> <style type="text/css"> input{ border: 1px solid black; text-align: right; font-size:20px; } </style></head><body> <input type="text" id="text" value="0" >秒 <br> <input type="button" value="開始計(jì)時(shí)" id="btn1"> <input type="button" value="停止計(jì)時(shí)" id="btn2"> <script type="text/javascript"> var time = 0; var seconde=0; var btn1 = document.getElementById("btn1"); var btn2 = document.getElementById("btn2"); var text = document.getElementById("text"); function getStyle(elem, prop) { if (window.getComputedStyle) { return window.getComputedStyle(elem, null)[prop]; } else { return elem.currentStyle[prop]; } } var count = 1;//設(shè)置時(shí)間戳 btn1.addEventListener("click",showTime) function showTime(e) { if(count){ time = setInterval(function () { seconde++; text.value = seconde; }, 1000) count =0; } } btn2.addEventListener("click",stopTime) function stopTime(){ clearInterval(time); count =1; } </script></body></html>以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持錯(cuò)新站長站。
新聞熱點(diǎn)
疑難解答
圖片精選