策略模式
作者: 阿蒙 时间: 2020-2-21 标签: 设计模式 浏览: 1374 评论: 0
定义:定义一系列的算法,把它们一个个封装起来,并且使他们可以相互替换。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-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>
<script>
let tween = {
linear: (t, b, c, d) => {
return c*t/d + b;
},
easeIn: (t, b, c, d) => {
return c * (t /= d) * t + b;
},
strongEaseIn: (t, b, c, d) => {
return c * (t /= d) * t * t * t * t + b;
},
strongEaseOut: (t, b, c, d) => {
return c * ((t = t / d -1) * t * t * t * t + 1) + b;
},
sineaseIn: (t, b, c, d) => {
return c * (t /= d) * t * t + b;
},
sineaseOut: (t, b, c, d) => {
return c * ((t = t / d - 1) * t * t + 1) + b;
}
};
let Animate = function (dom) {
this.dom = dom;
this.startTime = 0;
this.startPos = 0;
this.endPos = 0;
this.propertyName = null;
this.easing = null;
this.duration = null;
};
Animate.prototype.start = function (propertyName, endPos, duration, easing) {
this.startTime = +new Date;
this.startPos = this.dom.getBoundingClientRect()[propertyName];
this.propertyName = propertyName;
this.endPos = endPos;
this.duration = duration;
this.easing = tween[easing];
let self = this;
let timeId = setInterval(function () {
if (self.step() === false) {
clearInterval(timeId);
}
}, 19)
};
Animate.prototype.step = function () {
let t = +new Date;
if (t >= this.startTime + this.duration) {
this.update( this.endPos );
return false;
}
let pos = this.easing( t - this.startTime, this.startPos, this.endPos - this.startPos, this.duration);
this.update(pos);
};
Animate.prototype.update = function (pos) {
this.dom.style[this.propertyName] = pos + 'px';
};
let div = document.getElementById("div");
let animate = new Animate(div);
animate.start('left', 500, 1000, 'strongEaseOut');
</script>
</body>
</html>
本文相关标签: 设计模式笔记
发表评论: