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" /> <style> .container { width: 300px; height: 100px; background-color: #eee; padding: 20px 10px; margin: 100px auto; } .box { width: 100px; height: 30px; margin: 30px auto; } .box span { color: red; font-size: 20px; display: inline-block; padding: 0 5px; } </style> <title>Document</title> </head> <body> <div class="container"> <input type="number" id="time" /> <button id="btn1">计时开始</button> <button id="btn2">暂停</button> <button id="btn3">结束</button> <div class="box">倒计时<span></span>秒</div> </div> </body> <script> var time = document.querySelector('#time') var btn1 = document.querySelector('#btn1') var btn2 = document.querySelector('#btn2') var btn3 = document.querySelector('#btn3') var span = document.querySelector('.box').children[0] // 计时 btn1.addEventListener('click', function() { var val = time.value time.value = '' if (!val) { alert('请输如大于0的时间,单位:秒') } else { var timeId = funTime(val) } // 暂停 btn2.addEventListener('click', function() { var txt = btn2.innerHTML if (span.innerHTML) { if (txt == '暂停') { clearInterval(timeId) btn2.innerHTML = '开始' } else { timeId = funTime(span.innerHTML) btn2.innerHTML = '暂停' } } }) // 结束 btn3.addEventListener('click', function() { if (timeId) { clearInterval(timeId) span.innerHTML = '' } }) // 计时器函数 function funTime(val) { span.innerHTML = val var timer = setInterval(() => { if (val === 0) { clearInterval(timeId) span.innerHTML = '' alert('时间到!') } else { val-- span.innerHTML = val } }, 1000) return timer } }) </script> </html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章