使用回调和Promise两种方法实现3个小球依次移动
2018-01-14 19:29
573 查看
<!DOCTYPE html> <html> <head> <title>promise调用</title> <style type="text/css"> .ball{ width: 20px; height: 20px; border-radius: 50%; } .ball1{ background-color: red; } .ball2{ background-color: yellow; } .ball3{ background-color: 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 type="text/javascript"> let ball1 = document.querySelector(".ball1"); let ball2 = document.querySelector(".ball2"); let ball3 = document.querySelector(".ball3"); //原生回调方法 function animate(ball,distance,cb){ setTimeout(function(){ let marginLeft = parseInt(ball.style.marginLeft,10); if(marginLeft === distance){ cb&&cb() return; }else{ if(marginLeft < distance){ marginLeft++; }else{ marginLeft--; // debugger; } } ball.style.marginLeft = marginLeft + 'px'; 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,150,function(){ }) }) }) }) }) }) //promise 方法 function promiseAinmate(ball,distance) { return new Promise(function(resolve,reject) { function _animate(){ setTimeout(function(){ let marginLeft = parseInt(ball.style.marginLeft,10); if(marginLeft === distance){ resolve() return; }else{ if(marginLeft < distance){ marginLeft++; }else{ marginLeft--; // debugger; } } ball.style.marginLeft = marginLeft + 'px'; _animate(); },13) } _animate(); }) } promiseAinmate(ball1,100) .then(function(){ return promiseAinmate(ball2,200) }) .then(function(){ return promiseAinmate(ball3,300) }) .then(function(){ return promiseAinmate(ball3,150) }) .then(function(){ return promiseAinmate(ball2,150) }) .then(function(){ return promiseAinmate(ball1,150) }) </script> </body> </html>
相关文章推荐
- 两种方法使用jquery实现左右移动效果(包含each遍历方式)
- Struts2使用XML实现Validation校验数据的两种方法
- 两种方法使用js读写cookie实现一个底部广告浮层效果
- 使用递归和非递归两种方法实现二分查找!!!
- 学习并使用了两种linq to entity 的实现sql关键字in的查询方法
- 使用javascript和jquery两种方法,实现密码明文和密文的转换
- 使用layout方法实现控件的移动并且不影响点击事件
- c++实现回调函数及使用方法
- Linux系统下禁止非WHEEL用户使用SU命命的两种实现方法
- 实现冒泡排序。(排序整形数组)。使用数组和指针两种方法。
- c语言:实现对于给定的正整数N,依次打印出小于等于N的所有素数。两种方法及其优化
- 如何:使用回调方法实现异步 Web 服务客户端
- 使用presentViewController跳转到上上个页面,实现多层跳转的两种方法。
- n的k次方,使用递归的两种实现方法
- 在WCF中使用SoapHeader进行验证的两种实现方法
- 跨平台python异步回调机制实现和使用方法
- IOS入门——使用UIView简单实现霓虹灯(两种方法)
- 使用服务端和客户端两种方法 模拟网易邮箱实现全选,全不选的功能
- jquery使用animate方法实现控制元素移动
- 使用服务端和客户端两种方法 模拟网易邮箱实现全选,全不选的功能