js动画animate缓动效果setInterval()

<!DOCTYPE HTML>
<html>
 <head>
  <title>js动画animate缓动效果setInterval()</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) {
     //每次移动的距离 = (目标值-现在的位置)/10
     function move() {
     /*这个移动距离是个小数,可以选择往上取整,
     即 obj.style.marginLeft
      = obj.offsetLeft + Math.ceil((target - obj.offsetLeft) / 10) + 'px';*/
     
      obj.style.marginLeft = obj.offsetLeft + (target - obj.offsetLeft) / 10 + 'px';
      if(obj.offsetLeft == target) {
        clearTimeout(obj.timer);
       }
   }
   //用定时器让盒子动起来 
   obj.timer = setInterval(move, 100);
   }
   //调用animate函数,给定参数
   animate(box, 300);


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

猜你喜欢

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