练习3_BOM按钮倒计时.html 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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: #fff;
  12. box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
  13. border-radius: 10px;
  14. position: fixed;
  15. top: 50%;
  16. left: 50%;
  17. margin-left: -150px;
  18. margin-top: -150px;
  19. text-align: center;
  20. }
  21. .box .num {
  22. font-size: 50px;
  23. font-weight: bold;
  24. color: #333;
  25. }
  26. .box button {
  27. width: 100px;
  28. height: 50px;
  29. border: 1px solid black;
  30. border-radius: 5px;
  31. font-size: 25px;
  32. }
  33. </style>
  34. </head>
  35. <body>
  36. <div class="box">
  37. <p class="num">10</p>
  38. <button>开始</button>
  39. </div>
  40. <script>
  41. // 第一步获取元素
  42. // 获取按钮
  43. var oBtn = document.getElementsByTagName("button");
  44. // 把数组中的标签取出来
  45. oBtn = oBtn[0];
  46. // 获取数字标签
  47. var numEle = document.getElementsByClassName("num");
  48. // 把数组中的标签取出来
  49. numEle = numEle[0];
  50. // console.log(oBtn);
  51. // console.log(numEle);
  52. // 第二步绑定事件
  53. // 准备一个变量用来装递减的数字
  54. var num = 10;
  55. var timer = null;
  56. // 每次促发事件生成的事件处理函数不是同一个
  57. oBtn.onclick = function () {
  58. // 判断开始或结束
  59. // 获取按钮中的文字,根据文字判断开始或结束
  60. var btnText = oBtn.innerText;
  61. if (btnText == "开始") {
  62. oBtn.innerText = "暂停";
  63. // 第三步开始倒计时
  64. timer = setInterval(function () {
  65. //让数字开始递减
  66. num--;
  67. // 把递减之后的数字放到页面里
  68. numEle.innerText = num;
  69. }, 1000);
  70. } else {
  71. oBtn.innerText = "开始";
  72. // 清除定时器
  73. clearInterval(timer);
  74. }
  75. }
  76. </script>
  77. </body>
  78. </html>