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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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: #999;
  12. border-radius: 20px;
  13. box-shadow: 1px 1px 5px rgba(0,0,0,0.5);
  14. position: fixed;
  15. top: 50%;
  16. left: 50%;
  17. margin-top: -150px;
  18. margin-left: -150px;
  19. text-align: center;
  20. color: #fff;
  21. font-weight: bold;
  22. font-size: 50px;
  23. }
  24. p{
  25. margin-bottom: 0;
  26. margin-top: 80px;
  27. }
  28. button{
  29. width: 100px;
  30. height: 50px;
  31. font-size: 30px;
  32. }
  33. </style>
  34. </head>
  35. <body>
  36. <div class="box">
  37. <p>100</p>
  38. <button>开始</button>
  39. </div>
  40. <script>
  41. // 第一步 获取要控制的元素
  42. var oNum = document.getElementsByTagName("p");
  43. var oBtn = document.getElementsByTagName("button");
  44. // 定义start变量来控制开始和暂停
  45. var start = true;
  46. // 定义定时器数字
  47. var num = 100;
  48. // 定义定时器变量
  49. var timer = null;
  50. // 定义倒计时函数
  51. function fn(){
  52. timer = setInterval(function(){
  53. num--;
  54. oNum[0].innerText = num;
  55. },1000);
  56. }
  57. // 绑定事件
  58. oBtn[0].onclick = function(){
  59. // 修改按钮中的文字
  60. if(start){
  61. oBtn[0].innerText = "暂停";
  62. start = false;
  63. // 调用倒计时函数
  64. fn();
  65. }else{
  66. oBtn[0].innerText = "开始";
  67. start = true;
  68. // 暂停倒计时
  69. clearInterval(timer);
  70. }
  71. }
  72. </script>
  73. </body>
  74. </html>