標籤:ace http etc text ++ pat efault script mat
css樣式分為內聯樣式、內部樣式和外部樣式,然而object.style.xxx只能夠擷取內聯樣式的屬性值,內部樣式和外部樣式的css樣式擷取不到
js擷取方法使用document.defaultView.getComputedStyle()、currentStyle()
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <!-- <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> --> 7 <title>Promise animation</title> 8 <style> 9 .ball{10 width: 40px;11 height: 40px;12 border-radius: 20px;13 margin-left: 10px;14 }15 .ball1{16 background: red;17 }18 .ball2{19 background: yellow;20 }21 .ball3{22 background: green;23 }24 </style>25 </head>26 <body>27 <div class="ball ball1"></div>28 <div class="ball ball2"></div>29 <div class="ball ball3"></div>30 <script type="text/javascript">31 var ball1=document.querySelector(‘.ball1‘);32 var ball2=document.querySelector(‘.ball2‘);33 var ball3=document.querySelector(‘.ball3‘);34 35 //用於擷取外部引入的屬性值,解決margin-left未寫在行內擷取為空白的情況36 function getCurrentstyle(obj,prop){37 if (obj.currentStyle) //IE38 {39 return obj.currentStyle[prop];40 }41 else if (window.getComputedStyle) //非IE42 {43 property = prop.replace(/([A-Z])/g, "-$1");44 property = prop.toLowerCase();45 return document.defaultView.getComputedStyle(obj,null)[property];46 }47 return null;48 }49 50 function animate(ball,distance,cb){51 setTimeout(function(){52 var marginLeft=parseInt(getCurrentstyle(ball,‘margin-left‘),10);53 if (marginLeft===distance) {54 cb && cb();55 }else {56 if (marginLeft<distance) {57 marginLeft++;58 }else {59 marginLeft--;60 }61 ball.style.marginLeft=marginLeft+‘px‘;62 animate(ball,distance,cb)63 }64 },13)65 }66 animate(ball1,100,function(){67 animate(ball2,200,function(){68 animate(ball3,300,function(){69 animate(ball3,150,function(){70 animate(ball2,150,function(){71 animate(ball1,150,function(){72 //73 })74 })75 })76 })77 })78 })79 </script>80 </body>81 </html>
非內聯css樣式擷取方法