练习7_DOM进度条.html 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. .progress{
  9. width: 500px;
  10. height: 50px;
  11. border:3px solid black;
  12. border-radius: 10px;
  13. line-height: 50px;
  14. padding-left: 50px;
  15. box-sizing: border-box;
  16. position: relative;
  17. overflow: hidden;
  18. }
  19. .progress-bg{
  20. width: 0;
  21. height: 100%;
  22. background-color: blue;
  23. position: absolute;
  24. top: 0;
  25. left: 0;
  26. }
  27. .progress-num{
  28. position: relative;
  29. z-index: 1;
  30. }
  31. </style>
  32. </head>
  33. <body>
  34. <div class="progress">
  35. <span class="progress-num">0%</span>
  36. <div class="progress-bg"></div>
  37. </div>
  38. <button>开始</button>
  39. <script>
  40. // 第一步获取元素
  41. // 获取按钮
  42. var progressBtn = document.getElementsByTagName("button");
  43. progressBtn = progressBtn[0];
  44. // 获取进度条
  45. var progressBg = document.getElementsByClassName("progress-bg");
  46. progressBg = progressBg[0];
  47. // 获取进度条文字
  48. var progressNum = document.getElementsByClassName("progress-num");
  49. progressNum = progressNum[0];
  50. //用来存储定时器
  51. var timer = null;
  52. // 定义变量存储进度数字
  53. var num = 0;
  54. // 第二步为按钮绑定事件
  55. progressBtn.onclick = function(){
  56. // 通过offsetWidth 获取元素宽度
  57. var thisWidth = progressBg.offsetWidth;
  58. // 设置一个定时函数实现动画过度效果
  59. timer = setInterval(function(){
  60. thisWidth += 5;
  61. num++
  62. if(thisWidth <= 500){
  63. progressBg.style.width = thisWidth + "px";
  64. progressNum.innerText = num + "%";
  65. }else{
  66. clearInterval(timer);
  67. }
  68. // progressBg.style.width = (thisWidth + 10) + "px";
  69. },16);
  70. }
  71. </script>
  72. </body>
  73. </html>