getComputedStyle方法与currentStyle属性获取元素样式

1、getComputedStyle()

getComputedStyle是一个可以获取当前元素所有最终使用的CSS属性值(计算之后的最终结果,如2em计算后的结果。此外,即使没有CSS代码,也会把默认的祖宗八代都显示出来)。返回的是一个CSS样式声明对象([object CSSStyleDeclaration]),只读

/* 语法 */
var style = window.getComputedStyle("元素", "伪类");

/* 使用 */
var dom = document.getElementById("test"),
    style = window.getComputedStyle(dom , ":after");

额外提示下:Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) 之前,第二个参数“伪类”是必需的(如果不是伪类,设置为null),不过现在嘛,不是必需参数了。

2、getComputedStyle()与style的区别

我们使用element.style也可以获取元素的CSS样式声明对象,但是其与getComputedStyle方法还有有一些差异的。

1、 只读与可写
getComputedStyle方法只读,只能获取样式,不能设置;
而element.style能读能写,能屈能伸。

2、获取的对象范围
getComputedStyle方法获取的是最终应用在元素上的所有CSS属性对象(即使没有CSS代码,也会把默认的祖宗八代都显示出来);
而element.style只能获取元素style属性中的CSS样式。

因此对于一个光秃秃的元素<p>,getComputedStyle方法返回对象中length属性值(如果有)就是190+(据我测试FF:192, IE9:195, Chrome:253, 不同环境结果可能有差异), 而element.style就是0。

3、getComputedStyle与defaultView

jQuery源代码的css()方法实现不是使用window.getComputedStyle而是document.defaultView.getComputedStyle

实际上,使用defaultView基本上是没有必要的,getComputedStyle本身就存在window对象之中。

4、getComputedStyle兼容性

主流浏览器一般都支持,IE9+支持,IE6~8是不支持的。

5、IE的currentStyle属性

element.currentStyle,与element.style的 差别在于element.currentStyle返回的是元素当前应用的最终CSS属性值(包括外链CSS文件,页面中嵌入的<style>属性等)。

因此,从作用上将,getComputedStyle方法与currentStyle属性走的很近,形式上则style与currentStyle走的近。不过,currentStyle属性貌似不支持伪类样式获取,这是与getComputedStyle方法的差异,也是jQuery css()方法无法体现的一点。

//兼容代码
 var oStyle = this.currentStyle? this.currentStyle : window.getComputedStyle(this, null);
    alert(oStyle.height);

6、getPropertyValue方法与getAttribute方法

getComputedStyle方法与currentStyle属性其他具体差异还有很多,如FireFox浏览器下的float属性为‘cssFloat’,IE下为‘styleFloat’。

使用getPropertyValue或getAttribute方法就不需要对cssFloat与styleFloat的怪异写法与兼容性处理。

window.getComputedStyle(element, null).getPropertyValue("float");
style.getPropertyValue("border-top-left-radius");
//getPropertyValue不支持驼峰写法
style.getAttribute("float");
style.getAttribute("backgroundColor");
/ /getAttribute只支持驼峰写法

// 如果不考虑IE6浏览器,貌似也是可以这么写:
style.getAttribute("background-color");

7、写在最后

有了jQuery等优秀库,我们有熟悉底层的getComputedStyle方法的必要吗?
类似css()方法没有的功能——获取伪类元素样式。但从这一点上将,熟悉getComputedStyle方法有必要。

参考:张鑫旭http://www.zhangxinxu.com/wordpress/2012/05/getcomputedstyle-js-getpropertyvalue-currentstyle/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章