注意:函数需要传递2个参数,动画对象和移动到的距离。

    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>测试</title>
    8. <style>
    9. *{
    10. margin: 0;
    11. padding: 0;
    12. }
    13. div{
    14. position: absolute;
    15. left: 0;
    16. width: 100px;
    17. height: 100px;
    18. background-color: pink;
    19. }
    20. span{
    21. position: absolute;
    22. top: 100px;
    23. left: 0;
    24. display: block;
    25. width: 100px;
    26. height: 100px;
    27. background-color: purple;
    28. }
    29. </style>
    30. </head>
    31. <body>
    32. <div></div>
    33. <span></span>
    34. <script>
    35. //简单动画函数封装 obj目标对象 target目标位置
    36. function animate (obj,target) {
    37. //让盒子在当前位置+1距离
    38. //定时器重复操作,最后清除定时器
    39. var timer = setInterval(function(){
    40. //获得盒子当前的位置
    41. var x = obj.offsetLeft;
    42. if(x >= target){
    43. clearInterval(timer);
    44. }
    45. obj.style.left = x + 1 + 'px';
    46. },30);
    47. }
    48. //获取元素
    49. var div = document.querySelector('div');
    50. var span = document.querySelector('span');
    51. animate(div,300);
    52. animate(span,200);
    53. </script>
    54. </body>
    55. </html>

    .