JS---动画函数封装:设置任意的一个元素,移动到指定的目标位置

动画函数封装:设置任意的一个元素,移动到指定的目标位置

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>title</title>
  <style>
    div{
      width: 200px;
      height: 200px;
      background-color: red;
      /*脱离文档流*/
      position: absolute;
    }
  </style>
  <script>

    //设置任意的一个元素,移动到指定的目标位置
    function animate(element, target) {
      clearInterval(element.timeId);
      //定时器的id值存储到对象的一个属性中
      element.timeId = setInterval(function () {
        //获取元素的当前的位置,数字类型
        var current = element.offsetLeft;
        //每次移动的距离
        var step = 10;
        step = current < target ? step : -step;
        //当前移动到位置
        current += step;
        if (Math.abs(current - target) > Math.abs(step)) {
          element.style.left = current + "px";
        } else {
          //清理定时器
          clearInterval(element.timeId);
          //直接到达目标
          element.style.left = target + "px";
        }
      }, 20);
    }

  </script>
</head>
<body>


</body>
</html>

猜你喜欢

转载自www.cnblogs.com/jane-panyiyun/p/12029890.html
今日推荐