美文网首页
setInterval简单动画

setInterval简单动画

作者: 王远清orz | 来源:发表于2019-11-18 13:38 被阅读0次
 <style>
    body{
      margin: 0;
    }
    #box {
      position: relative;
      width: 100px;
      height: 100px;
      background-color: red;
    }

    #box1 {
      margin-top: 10px;
      position: relative;
      width: 100px;
      height: 100px;
      background-color: blue;
    }
  </style>

<body>
  <input type="button" id="btn" value="动画 800">
  <input type="button" id="btn1" value="动画 400">

  <div id="box">
  </div>
  <div id="box1">
  </div>
  <script>
    var btn = my$('btn');
    var btn1 = my$('btn1');
    var box = my$('box');
    var box1 = my$('box1');
    var timeId = null;
    btn.onclick = function () {
      animate(box, 800);
      animate(box1, 800)
    }

    btn1.onclick = function () {
      animate(box, 400);
      animate(box1, 400)
    }
    // 封装动画函数
    function animate(element, target) { //传 运动的元素 和 运动的距离两个参数

      // 通过判断,只允许一个定时器执行
      if (element.timeId) {           //element.timeId 让每一个盒子记录自己的timeId
        clearInterval(element.timeId);
        element.timeId = null;
      }
      element.timeId = setInterval(move, 30);

      function move() {
        // 定义每步移动距离
        var step = 10;
        // 如果当前位置大于目标位置,step应该为负数
        var current = element.offsetLeft;

        if (current > target) {
          step = - Math.abs(step);
        }
        if (Math.abs(current - target) < Math.abs(step)) {
          //清楚定时器
          clearInterval(element.timeId);
          //设置横坐标为定义的数
          element.style.left = target + 'px';
          return;
        }
        current += step;
        // style.left获取样式属性,是获取标签内style中的样式属性的值,如果没有该样式属性,则返回空字符串
        //box.offsetLeft是只读属性,无法赋值,这里需要同步offsetLeft的值和style.left的值,就是取消Body的margin值
        element.style.left = current + 'px';
      }
    }
  </script>
</body>

相关文章

网友评论

      本文标题:setInterval简单动画

      本文链接:https://www.haomeiwen.com/subject/knovictx.html