动画实现不了
按照你的代码写的,marginLeft 的值一直为0 怎么回事?
按照你的代码写的,marginLeft 的值一直为0 怎么回事?
2016-03-23
<!doctype> <html> <head> <title>Promise animation</title> <style> .ball{ width:40px; height:40px; border-radius:20px; } .ball1{ background:red; } .ball2{ background:yellow; } .ball3{ background:green; } </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,distance,cb){ setTimeout(function(){ var marginLeft =parseInt(ball.style.marginLeft,10) if (marginLeft === distance){ cb&&cb() } else{ if (marginLeft<distance){ marginLeft++ } else{ marginLeft-- } ball.style.marginLeft = marginLeft animate (ball,distance,cb) //不断重复动作 } },13) } animate(ball1,100,function(){ animate(ball2,200,function(){ animate(ball3,300,function(){ animate(ball3,150,function(){ animate(ball2,150,function(){ animate(ball1,100,function(){ // }) }) }) }) }) }) </script> </body> </html>
这个亲测无压力
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Promise animate</title> <style> .ball{ width: 40px; height: 40px; border-radius: 20px; } .ball1{ background: red; } .ball2{ background: yellow; } .ball3{ background: green; } </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, distance, callback){ setTimeout(function() { var marginLeft = parseInt(ball.style.marginLeft, 10); console.log(marginLeft); console.info(distance); if(marginLeft === distance){ callback && callback(); }else{ if(marginLeft < distance){ marginLeft++; }else{ marginLeft--; } ball.style.marginLeft = marginLeft + 'px'; animate(ball, distance, callback); } }, 13); } animate(ball1, 100, function(){ animate(ball2, 200, function() { animate(ball3, 300, function() { animate(ball3, 150, function() { animate(ball2, 150, function() { animate(ball1, 150, function() { }) }) }) }) }) }); </script> </body> </html>
代码可用,在chrome上跑看看。
举报