基础版(最大缺点就是没有控制当多次点击开始时,计时器计时效果会加速)
<!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> <style> #div1 { width: 100px; height: 200px; border: 1px solid black; background-color: coral; margin:300px auto; } #div1 span{ font-size: 22px; } #div1 button{ width: 100px; margin-top: 20px; font-size: 16px; background-color: black; color: crimson; } </style> <script> function $(id){ return document.getElementById(id); } var i = 0;//总秒数 var time = null//定义成全局变量方便后面的关闭定时器 window.onload = function(){ $("start").onclick = function(){ time = setInterval(function(){ i++; $("s").innerHTML = i%60; $("s").innerHTML = doublenumber( $("s").innerHTML); $("m").innerHTML = parseInt(i/60) %60; $("m").innerHTML = doublenumber( $("m").innerHTML); $("h").innerHTML = parseInt(i/3600); $("h").innerHTML = doublenumber( $("h").innerHTML); },1000); }; $("pause").onclick = function(){ clearInterval(time);//关闭计数器 } $("reset").onclick = function(){ clearInterval(time); i = 0;//一定要将i(总秒数归零) $("s").innerHTML = '00'; $("m").innerHTML = '00'; $("h").innerHTML = '00'; };} function doublenumber(n){ if(n>=0&&n<=9) return '0'+n; else return n;
} </script> <body> <div id = "div1"> <span id="h">00</span> <span id="m">00</span> <span id="s">00</span> <br/> <button id="start">开始</button> <button id="pause">暂停</button> <button id="reset">复位</button> </div> </body> </html>