js用策略思维做的小球滑动

用策略思维做的小球滑动

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <div style="position:absolute;background:blue" id="div">我是div</div>
</body>
<script>
  var tween = {
    linear: function (t, b, c, d) {
      return c * t / d + b;
    },
    easeIn: function (t, b, c, d) {
      return c * (t /= d) * t + b;
    },
    strongEaseIn: function (t, b, c, d) {
      return c * (t /= d) * t * t * t * t + b;
    },
    strongEaseOut: function (t, b, c, d) {
      return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
    },
    sineaseIn: function (t, b, c, d) {
      return c * (t /= d) * t * t + b;
    },
    sineaseOut: function (t, b, c, d) {
      return c * ((t = t / d - 1) * t * t + 1) + b;
    }
  };
  var Animate = function (dom) {
    this.dom = dom; // 进行运动的dom 节点
    this.startTime = 0; // 动画开始时间
    this.startPos = 0; // 动画开始时,dom 节点的位置,即dom 的初始位置
    this.endPos = 0; // 动画结束时,dom 节点的位置,即dom 的目标位置
    this.propertyName = null; // dom 节点需要被改变的css 属性名
    this.easing = null; // 缓动算法
    this.duration = null; // 动画持续时间
  };
  Animate.prototype.start = function (propertyName, endPos, duration, easing) {
    this.startTime = +new Date; // 动画启动时间
    this.startPos = this.dom.getBoundingClientRect()[propertyName]; // dom 节点初始位置
    this.propertyName = propertyName; // dom 节点需要被改变的CSS 属性名
    this.endPos = endPos; // dom 节点目标位置
    this.duration = duration; // 动画持续事件
    this.easing = tween[easing]; // 缓动算法
    var self = this;
    var timeId = setInterval(function () { // 启动定时器,开始执行动画
      if (self.step() === false) { // 如果动画已结束,则清除定时器
        clearInterval(timeId);
      }
    }, 16);
  };
  Animate.prototype.step = function () {
    var t = +new Date; // 取得当前时间
    if (t >= this.startTime + this.duration) { // (1)
      this.update(this.endPos); // 更新小球的CSS 属性值
      return false;
    }
    var pos = this.easing(t - this.startTime, this.startPos, this.endPos - this.startPos, this.duration);
    // pos 为小球当前位置
    this.update(pos); // 更新小球的CSS 属性值
  };

  Animate.prototype.update = function (pos) {
    this.dom.style[this.propertyName] = pos + 'px';
  };

  var div = document.getElementById('div');
  var animate = new Animate(div);
  animate.start('left', 500, 1000, 'linear');
  // animate.start( 'top', 1500, 500, 'strongEaseIn' );
</script>

</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值