js动画animate缓动效果添加回调函数callback

<!DOCTYPE HTML>
<html>
 <head>
  <title>js动画animate缓动效果添加回调函数callback</title>
  <meta charset="utf-8" />
  <style>
   * {
    margin: 0;
    padding: 0;
    }
   #box {
    
    width: 100px;
    height: 100px;
    background-color: pink;
   }
  </style>
 </head>
 <body>
  <div id="box"> </div>
  <script>
   //第一步 获得盒子的当前位置
   var box = document.getElementById('box');
   //用animate函数把内容封装起来
   function animate(obj, target, callback) {
     //每次移动的距离 = (目标值-现在的位置)/10
     function move() {
      var step = (target - obj.offsetLeft) / 10;
      step = step > 0 ? Math.ceil(step) : Math.floor(step);
      obj.style.marginLeft = obj.offsetLeft + step + 'px';
      if(obj.offsetLeft == target) {
        clearTimeout(obj.timer);
          if(callback) {
            callback();
           }
       }
   }
   //用定时器让盒子动起来 
   obj.timer = setInterval(move, 300);
   }
   //调用animate函数
   animate(box, 300, function() {box.style.backgroundColor = 'red';});


  </script>
 </body>
</html>
原创文章 22 获赞 4 访问量 2592

猜你喜欢

转载自blog.csdn.net/tuzi007a/article/details/105464648