1. js实现动画
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>animate</title> <style> .ball { width: 40px; height: 40px; margin-bottom: 5px; border-radius: 20px; } .ball1 { background: red; } .ball2 { background: blue; } .ball3 { background: yellow; } </style></head><body> <div class="ball ball1" style="margin-left: 0"></div> <div class="ball ball2" style="margin-left: 0"></div> <div class="ball ball3" style="margin-left: 0"></div> <script> var ball1 = document.querySelector(".ball1"); var ball2 = document.querySelector(".ball2"); var ball3 = document.querySelector(".ball3"); function animate(ball, left, callback) { setTimeout(function () { var marginLeft = parseInt(ball.style.marginLeft, 10); if (marginLeft === left) { callback && callback(); } else { if (marginLeft < left) { marginLeft += 2; } else { marginLeft -= 2; } ball.style.marginLeft = marginLeft + "px"; animate(ball, left, callback); } }, 13); } animate(ball1, 100, function () { animate(ball2, 200, function () { animate(ball3, 300, function () { animate(ball1, 200, function () { animate(ball3, 200, function () { animate(ball2, 180, function () { animate(ball2, 220, function () { animate(ball2, 200, function () { console.log("over"); }) }) }) }) }) }) }) }); </script></body></html>
上述代码就可以实现一个动画。注意下面几点:
•动画的实现往往依赖于setTimeout。
•注意ele.style.marginLeft如果开始能够获取,必须从元素的style中设置了才能获取,否则获取不到。
•利用callback可以实现虽然使用了setTimeout还能串行执行。
但是这产生了回调地狱,代码简单点还好说,一旦代码复杂了,我们将很难处理其中的逻辑。所以这时就可以用到es6中的promise了。
Promise的写法如下:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>animate</title> <style> .ball { width: 40px; height: 40px; margin-bottom: 5px; border-radius: 20px; } .ball1 { background: red; } .ball2 { background: blue; } .ball3 { background: yellow; } </style></head><body> <div class="ball ball1" style="margin-left: 0"></div> <div class="ball ball2" style="margin-left: 0"></div> <div class="ball ball3" style="margin-left: 0"></div> <script> var ball1 = document.querySelector(".ball1"); var ball2 = document.querySelector(".ball2"); var ball3 = document.querySelector(".ball3"); function promiseAnimate(ball, left) { return new Promise(function (resolve, reject) { function animate(ball, left) { setTimeout(function () { var marginLeft = parseInt(ball.style.marginLeft, 10); if (marginLeft === left) { resolve(); } else { if (marginLeft < left) { marginLeft += 2; } else { marginLeft -= 2; } ball.style.marginLeft = marginLeft + "px"; animate(ball, left); } }, 13); } animate(ball,left); }); } promiseAnimate(ball1, 500) .then(function () { return promiseAnimate(ball2, 200); }) .then(function () { return promiseAnimate(ball3, 300); }) .then(function () { return promiseAnimate(ball1, 200); }) .then(function () { return promiseAnimate(ball3, 200); }) .then(function () { return promiseAnimate(ball2, 180); }) .then(function () { return promiseAnimate(ball2, 220); }) .then(function () { return promiseAnimate(ball2, 200); }) </script></body></html>
新闻热点
疑难解答
图片精选