<!DOCTYPE html> <body> <div id="gift-fly" style=" position: absolute; width: 50px;height: 50px;background-color: #327dff "> 动画盒子</div> </body> <script> let flyDiv = document.getElementById("gift-fly") animate(flyDiv, {"left": 500}, 3000, "easeIn").then(res => { console.log("飞入动画执行完了") animate(flyDiv, {"left": 0}, 3000, "easeOut").then(res => { console.log("飞出动画执行完了") }) })
function animate(elem, params, duration, easing) { return new Promise(success => {
let tween = { easeIn: function (t, b, c, d) { return c * (t /= d) * t + b; }, easeOut: function (t, b, c, d) { return -c * (t /= d) * (t - 2) + b; } }; let attribute = { get: function (elem, attr) { let val; if (elem.currentStyle) { if (attr === "opacity") { val = elem.filters.alpha[attr]; } else { val = elem.currentStyle[attr]; } } else { val = getComputedStyle(elem)[attr]; if (attr === "opacity") { val = 100 * val; } } return val; }, set: function (elem, attr, val) { if (attr == 'opacity') { elem.style.filter = 'alpha(opacity=' + (val) + ')'; elem.style.opacity = (val) / 100; } else { elem.style[attr] = val + 'px'; } } }; let effect = { animate: function (elem, params, duration, easing) { let dt = new Date().getTime(), b = 0, c = 0, d = duration || 500, fps = 1000 / 60;
let changes = [];
for (let attr in params) { b = parseFloat(attribute.get(elem, attr)); c = params[attr] - b;
changes.push({
attr: attr,
b: b,
c: c }); }
easing = easing || "easeOut"; setTimeout(function () { let t = new Date().getTime() - dt; let b, c, attr; for (let i = 0; i < changes.length; i++) { b = changes[i].b; c = changes[i].c; attr = changes[i].attr;
attribute.set(elem, attr, tween[easing](t, b, c, d)); if (d <= t) { attribute.set(elem, attr, params[attr]); success(); return; } } setTimeout(arguments.callee, fps); }, fps); } }; effect.animate(elem, params, duration, easing); }) } </script> </html>
|