querySelector() 方法返回文檔中匹配指定 CSS 選擇器的一個元素。html
獲取文檔中有 "targnode
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Promise animation</title> <style> .ball{width: 40px; height: 40px; border-radius: 20px; } .ball1{background: crimson;} .ball2{background: darkorange;} .ball3{background: darkgreen;} </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); //表示以10爲基數 if (marginLeft === distance){ //當球運動到指望地點 cb && cb(); }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(){ }) }) }) }) }) }) </script> </body> </html>
et" 屬性的第一個 <a> 元素:document.querySelector("a[target]")npm
首先nodeJS安裝目錄 :E:\nodeJS\nodejs\node_modules\npm\node_modules 下安裝 bluebird庫promise
而後在 node_modules下就能夠找到bluebird文件夾,找到bluebird.js引入項目瀏覽器
<script src="bluebird.js"></script> 而後在瀏覽器中就會有一個全局變量 Promise函數
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Promise animation</title> <style> .ball{width: 40px; height: 40px; border-radius: 20px; } .ball1{background: crimson;} .ball2{background: darkorange;} .ball3{background: darkgreen;} </style> <script src="bluebird.js"></script> </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'); var Promise = window.Promise; function promiseAnimate(ball,distance){ return new Promise(function(resolve,reject){ function _animate(){ //animate加下劃線,變爲私有函數 setTimeout(function(){ var marginLeft = parseInt(ball.style.marginLeft,10); //表示以10爲基數 if (marginLeft === distance){ //當球運動到指望地點 resolve() ; //<====================注意帶() }else{ if(marginLeft <distance){ marginLeft++; }else{ marginLeft --; } ball.style.marginLeft = marginLeft +'px'; //球位置改變 _animate();//<======================================== } },13); }; _animate();//<========================第一次調用 }) } promiseAnimate(ball1,100) .then(function(){ return promiseAnimate(ball2 ,200) }) .then(function(){ return promiseAnimate(ball3 ,300) }) .then(function(){ return promiseAnimate(ball3 ,150) }) .then(function(){ return promiseAnimate(ball2 ,150) }) .then(function(){ return PromiseAnimate(ball1 ,150) }) </script> </body> </html>