為什么把margin-left寫在css里就不能用ball.style.marginLeft了?
<!doctype html>
<html lang="en">
<head>
? ?<meta charset="UTF-8">
? ?<title>Promise</title>
? ?<style>
? ? ? ?.ball{width:40px;height: 40px;border-radius: 50%; margin-left: 0px;}
? ? ? ?.ball1{background: red;margin-left: 0px;}
? ? ? ?.ball2{background: green;}
? ? ? ?.ball3{background: blue;}
? ?</style>
</head>
<body>
? ?<div class="ball ball1" ></div>
? ?<div class="ball ball2" ></div>
? ?<div class="ball ball3" ></div>
<script>
? ?var ball1 = document.querySelector('.ball1');
? ?var ball2 = document.querySelector('.ball2');
? ?var ball2 = document.querySelector('.ball3');
? ?function ani(ball,distance,cb){
? ? ? ?setTimeout(function(){
? ? ? ? ? ?var marle = parseInt(ball.style.marginLeft,10);
? ? ? ? ? ?if(marle === distance){
? ? ? ? ? ? ? ?cb && cb();
? ? ? ? ? ?}else{
? ? ? ? ? ? ? ?if(marle < distance){
? ? ? ? ? ? ? ? ? ?marle ++ ;
? ? ? ? ? ? ? ?}else{
? ? ? ? ? ? ? ? ? ?marle -- ;
? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ?ball.style.marginLeft = marle + "px";
? ? ? ? ? ? ? ?ani(ball,distance,cb)
? ? ? ? ? ?}
? ? ? ?},13)
? ?}
? ?//ani(ball1,100,function(){})
</script>
</body>
</html>
如果 這樣寫 ?而不是寫行內 ? ?就無法用var marle = parseInt(ball.style.marginLeft,10); ? 這是為什么
2016-09-27
用style獲取css樣式,只能獲取到寫到標簽內的樣式。參考網址:http://www.cnblogs.com/liulin0524/p/5315908.html
2016-09-26
js里獲取style里的樣式屬性不同于直接獲取dom節點里的屬性
可借鑒
function GetCurrentStyle (obj, prop) {?????
??? if (obj.currentStyle) {????????
??????? return obj.currentStyle[prop];?????
??? }??????
??? else if (window.getComputedStyle) {????????
??????? propprop = prop.replace (/([A-Z])/g, “-$1″);???????????
??????? propprop = prop.toLowerCase ();????????
??????? return document.defaultView.getComputedStyle (obj,null)[prop];?????
??? }??????
??? return null;???
} ?
alert(GetCurrentStyle(dd,”width”)); ???