JavaScript實現一定時長下點擊次數 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale= ...
JavaScript實現一定時長下點擊次數
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div class="time"> 倒計時:<span>60</span> </div> <div class="clickNum"> 點擊次數:<span>0</span> </div> <button class="btnClick">點擊</button> <button class="btnReset">重置</button> <script> var timer = null,//計時器id duration = 60,//倒計時時長 frequency = 0;//點擊次數 var time = document.querySelector(".time span"); var clickNum = document.querySelector(".clickNum span"); var btnClick = document.querySelector(".btnClick"); var btnReset = document.querySelector(".btnReset"); btnClick.onclick = function () { if (frequency === 0) { //第一次點擊開始計時 startTime(); } if(duration === 0){//倒計時為0 return; } frequency++; clickNum.innerText = frequency;//記錄點擊次數 } btnReset.onclick = function(){ duration = 60; frequency = 0; clickNum.innerText = frequency;//點擊次數重置為0 time.innerText = duration;//倒計時長重置為60; clearInterval(timer);//清除計時器 timer = null; } //開始計時 function startTime() { if (timer) { //計時器有值,返回 return; } timer = setInterval(function () { duration--; time.innerText = duration; if(duration === 0){ clearInterval(timer); timer = null; } }, 30); } </script> </body> </html>index.html
效果展示: