1. //简单动画函数封装 obj目标对象 target目标位置
    2. //给不同的元素指定了不同的定时器
    3. //缓动动画
    4. function animate (obj,target,callback) {
    5. clearInterval(obj.timer);
    6. //让盒子在当前位置+1距离
    7. //定时器重复操作,最后清除定时器
    8. obj.timer = setInterval(function(){
    9. //步长值写到定时器的里面
    10. var step = (target - obj.offsetLeft) / 10;
    11. step = step > 0 ? Math.ceil(step) : Math.floor(step);
    12. //获得盒子当前的位置
    13. var x = obj.offsetLeft;
    14. if(x == target){
    15. clearInterval(obj.timer);
    16. //回调函数写在定时器结束的位置
    17. if(callback){
    18. //调用函数
    19. callback();
    20. }
    21. }
    22. obj.style.left = x + step + 'px';
    23. },15);
    24. }
    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. <script src="./animate.js"></script>
    9. <style>
    10. .sliderbar {
    11. position: fixed;
    12. right: 0;
    13. bottom: 100px;
    14. width: 40px;
    15. height: 40px;
    16. text-align: center;
    17. line-height: 40px;
    18. cursor: pointer;
    19. color: #fff;
    20. }
    21. .con {
    22. position: absolute;
    23. left: 0;
    24. top: 0;
    25. width: 200px;
    26. height: 40px;
    27. background-color: purple;
    28. z-index: -1;
    29. }
    30. </style>
    31. </head>
    32. <body>
    33. <div class="sliderbar">
    34. <span>⬅</span>
    35. <div class="con">问题反馈</div>
    36. </div>
    37. <script>
    38. //获取元素
    39. var sliderbar = document.querySelector('.sliderbar');
    40. var con = document.querySelector('.con');
    41. var span = document.querySelector('span');
    42. sliderbar.addEventListener('mouseenter',function(){
    43. animate(con,-160,function(){
    44. span.innerHTML = '➡';
    45. });
    46. });
    47. sliderbar.addEventListener('mouseleave',function(){
    48. animate(con,0,function(){
    49. span.innerHTML = '⬅';
    50. });
    51. });
    52. </script>
    53. </body>
    54. </html>

    .