1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| <!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>JS策略模式的应用</title> </head>
<body> <div style="position:absolute;background:blue; width: 100px;height: 100px;color: #fff;" id="div">我是div</div> <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; 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]; var self = this; var timeId = setInterval(function () { if (self.stop() === false) { clearInterval(timeId); } }, 19); }; Animate.prototype.stop = function () { var t = +new Date; if (t >= this.startTime + this.duration) { this.update(this.endPos); return false; } var 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'; };
var div = document.getElementById('div'); var animate = new Animate(div); animate.start('left', 400, 1000, 'sineaseOut'); </script> </body>
</html>
|