练习3_按钮倒计时.html 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <style>
  8. .box{
  9. width: 400px;
  10. height: 400px;
  11. background-color: #999;
  12. overflow: hidden;
  13. position: absolute;
  14. left: 50%;
  15. top:50%;
  16. margin-top: -200px;
  17. margin-left: -200px;
  18. }
  19. .box .num{
  20. font-size: 50px;
  21. font-weight: bolder;
  22. text-align: center;
  23. margin-top: 100px;
  24. }
  25. .box .btn{
  26. width: 100px;
  27. height: 50px;
  28. border:1px solid black;
  29. text-align: center;
  30. line-height: 50px;
  31. margin: 0 auto;
  32. }
  33. </style>
  34. </head>
  35. <body>
  36. <div class="box">
  37. <div class="num">100</div>
  38. <div class="btn">开始</div>
  39. </div>
  40. <script>
  41. var oNum = document.getElementsByClassName('num')[0];
  42. var oBtn = document.getElementsByClassName('btn')[0];
  43. // 存储当前状态 true 代表暂停状态 false 代表运行状态
  44. var flag = true;
  45. var timer = 0;
  46. oBtn.onclick = function(){
  47. if(true){
  48. flag = false;
  49. oBtn.innerText = '暂停';
  50. timer = setInterval(function(){
  51. oNum.innerText --;
  52. },1000);
  53. }else{
  54. // 更正状态值
  55. flag = true;
  56. oBtn.innerText = '开始';
  57. clearInterval(timer);
  58. }
  59. }
  60. </script>
  61. </body>
  62. </html>