js动画实现setInterval(),让盒子自己动起来

<!DOCTYPE HTML>
<html>
 <head>
  <title>js动画实现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');
   //第二步  让盒子在当前位置移动1个距离
   function go() {
    box.style.marginLeft = box.offsetLeft + 10 + 'px';
       if(box.offsetLeft == 100) {
      clearTimeout(goahead);
    }
    }
   //或者给div一个定位 position: absolute; marginLeft换成left
   //console.log(box.offsetLeft);
   //第三步  利用定时器不断重复这个操作。
   var goahead = setInterval(go, 1000);
   //第四步  加一个结束定时器的条件

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

猜你喜欢

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