01.定时器的应用一.html 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <style>
  9. /* 清除默认样式 */
  10. * {
  11. margin: 0;
  12. padding: 0;
  13. }
  14. #box1 {
  15. width: 100px;
  16. height: 100px;
  17. background-color: red;
  18. position: absolute;
  19. /*
  20. 增加一个left:0,主要是解决部分IE浏览器不能正常获取box1的原始left值的问题
  21. */
  22. left: 0;
  23. }
  24. </style>
  25. <script>
  26. window.onload = function () {
  27. //获取box1
  28. var box1 = document.getElementById('box1');
  29. //获取btn01
  30. var btn01 = document.getElementById('btn01');
  31. //定义一个变量,用来保存定时器的标识
  32. var timer;
  33. //点击按钮以后,box1向右移动(left值增大)
  34. btn01.onclick = function () {
  35. /**
  36. * 每次点击按钮,都会打开一个定时器,如果连续点击按钮,
  37. * 会打开多个定时器,为了确保每次点击都只打开一个定时器,
  38. * 就需要在一进入单击响应函数时,先关闭上一个定时器,
  39. * 所以,也需要把定时器的标识设置为一个全局变量
  40. */
  41. //关闭上一个定时器
  42. clearInterval(timer);
  43. //开启定时器,用来执行动画效果
  44. timer = setInterval(function () {
  45. //获取box1的原来的left值
  46. var oldValue = parseInt(getStyle(box1, "left"));
  47. //在旧值的基础上增加
  48. var newValue = oldValue + 19;
  49. //判断newValue是否大于500
  50. if (newValue > 500) {
  51. newValue = 500;
  52. };
  53. //将新值设置给box1
  54. box1.style.left = newValue + 'px';
  55. //当元素移动到800px时,使其停止执行动画
  56. if (newValue == 500) {
  57. clearInterval(timer);
  58. };
  59. }, 30);
  60. };
  61. };
  62. function getStyle(obj, name) {
  63. if (window.getComputedStyle) {
  64. //正常浏览器的方式,具有getComputedStyle()方法
  65. return getComputedStyle(obj, null)[name];
  66. } else {
  67. //IE8的方式,没有getComputedStyle()方法
  68. return obj.currentStyle[name];
  69. };
  70. };
  71. </script>
  72. </head>
  73. <body>
  74. <button id="btn01">点击按钮以后box1向右移动</button>
  75. <br><br>
  76. <div id="box1"></div>
  77. <!-- 设置一条参考线,用来判断box1是否移动了想要的距离 -->
  78. <div style="width: 0;
  79. height: 1000px;
  80. border-left: 1px black solid;
  81. position: absolute;
  82. left: 500px;
  83. top: 0;"></div>
  84. </body>
  85. </html>