window.getComputedStyle
說明:
getComputedStyle()返回元素的所有css屬性的計算值
語法:
var style = window.getComputedStyle(element[, pseudoElt]);
參數說明:
element:目標元素的DOM對象
pseudoElt:指明要匹配的偽元素,對于普通元素必須指定為null(或省略)
返回值style為CSSStyleDeclaration對象.
getComputedStyle與dom.style的區(qū)別
getComputedStyle獲取的是所有css屬性的計算值
dom.style返回的是行內的css屬性計算值
getComputedStyle獲取的值是只讀的并且可被用于檢測元素的樣式(包括style屬性和外部樣式).而elt.style可被用于設置指定元素的樣式.
兼容IE
萬惡的IE不支持此方法橘券,它有自己的一個實現方式,那就是currentStyle,不同于全局方法getComputedStyle扒最,它是作為DOM元素屬性存在的,如:obj.currentStyle.paddingLeft,在IE中就獲取到對象的左內邊距了,兼容性的寫法如下: 復制代碼 代碼如下: return window.getComputedStyle ? window.getComputedStyle(obj,null).paddingLeft : obj.currentStyle.paddingLeft; 這樣渔欢,就能在IE及FF中返回對象的當前樣式信息了。
demo
html
<div id="demo" style="color:blue;font-size:20px">1111</div>
css
#demo{
width:200px;
height:200px;
background:red;
}
javascript
var demo1 = document.getElementById("demo");
var txt = window.getComputedStyle(demo1);
var txt1 = demo1.style;
console.log(txt,txt1);
這里color和font-size是行內樣式 getComputedStyle是可以得到所有樣式計算值瘟忱,而dom.style是只可以得到行內的樣式計算值奥额。
輸出如下
QQ截圖20170622143439.png
展開可以看到 兩個方法返回的都是CSSStyleDeclaration對象,該對象具有dom的css樣式計算值访诱。
1.getComputedStyle方法不僅可以得到行內樣式計算值垫挨,也可以得到id樣式計算值
2.dom.style只能得到行內樣式計算值,id樣式計算值都為空触菜。