练习题2_按钮倒计时.html 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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: 300px;
  10. height: 300px;
  11. background-color: #aaa;
  12. position: fixed;
  13. top: 50%;
  14. left: 50%;
  15. margin-top: -150px;
  16. margin-left: -150px;
  17. text-align:center;
  18. }
  19. p{
  20. font-size: 50px;
  21. color: #fff;
  22. font-weight: bold;
  23. text-align: center;
  24. }
  25. button{
  26. width: 100px;
  27. height: 50px;
  28. background-color:#fff;
  29. font-size:30px;
  30. }
  31. </style>
  32. </head>
  33. <body>
  34. <div class="box">
  35. <p>100</p>
  36. <button>开始</button>
  37. </div>
  38. <script>
  39. // 第一步:获取要控制的元素
  40. var num = document.getElementsByTagName("p")[0];
  41. var btn = document.getElementsByTagName("button")[0];
  42. var timer = 0;
  43. // 第二步:给按钮绑定事件
  44. btn.onclick = function(){
  45. if(btn.innerText == "开始"){
  46. btn.innerText = "暂停";
  47. // 开始倒计时-1
  48. timer = setInterval(function(){
  49. num.innerText--;
  50. },1000)
  51. console.log(timer);
  52. }else{
  53. btn.innerText = "开始"
  54. // 停止定时器
  55. console.log(timer)
  56. clearInterval(timer)
  57. }
  58. }
  59. // 如果使用on绑定事件绑定多次那么后边绑定的会覆盖前面绑定的事件
  60. // var a = 1;
  61. // var a = 2;
  62. // btn.onclick = function(){
  63. // console.log("hello")
  64. // }
  65. </script>
  66. </body>
  67. </html>