代码如下,只有第一个小球会动,然后就没然后了~~
<script type="text/javascript"> var ball1 = document.querySelector('.ball1'); var ball2 = document.querySelector('.ball2'); var ball3 = document.querySelector('.ball3'); var Promise = window.Promise; function p_animate(ball,distance){ return new Promise(function(resolve,reject){ function _animate(){ setTimeout(function(){ var marginLeft = ball.style.marginLeft==''?0:parseInt(ball.style.marginLeft); if (marginLeft == distance) { resolve; }else{ if (marginLeft<distance) { marginLeft++; }else{ marginLeft--; }; ball.style.marginLeft = marginLeft+'px'; } _animate(); },13); } _animate() }) } p_animate(ball1,100) .then(function(){ return p_animate(ball2,200) }) .then(function(){ return p_animate(ball3,300) }) .then(function(){ return p_animate(ball3,150) }) .then(function(){ return p_animate(ball2,150) }) .then(function(){ return p_animate(ball1,150) }) </script>
牛奶老哥哥