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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章