javascript获取元素CSS值之getComputedStyle方法



javascript获取元素CSS值之getComputedStyle方法。jQuery的CSS()方法,其底层运作就应用了getComputedStyle以及getPropertyValue方法

getComputedStyle是一个可以获取当前元素所有最终使用的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),不过现在参数不是必需的了。
getComputedStyle与style的区别
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。
getComputedStyle与defaultView
getComputedStyle兼容性
对于桌面设备:
Chrome Firefox (Gecko) Internet Explorer Opera Safari
基本支持 支持 支持 9 支持 支持
伪类元素支持 支持 支持 不支持 不支持 支持
对于手机设备:
Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
基本支持 支持 支持 WP7 Mango 支持 支持
伪元素支持 ? ? 不支持 ? ?
打问号的表示没有测试,是否兼容不知。
我们先把注意力放在桌面设备上,可以看到,getComputedStyle方法IE6~8是不支持的。不过,IE自有自己的一套方法。
getComputedStyle与currentStyle
currentStyle是IE浏览器自己的一个属性,其与element.style可以说是近亲,至少在使用形式上类似,element.currentStyle,差别在于element.currentStyle返回的是元素当前应用的最终CSS属性值(包括外链CSS文件,页面中嵌入的<style>属性等)。
因此,从作用上将,getComputedStyle方法与currentStyle属性走的很近,形式上则style与currentStyle走的近。不过,currentStyle属性貌似不支持伪类样式获取,这是与getComputedStyle方法的差异,也是jQuery css()方法无法体现的一点。
例如,我们要获取一个元素的高度,可以类似下面的代码:
alert((element.currentStyle? element.currentStyle : window.getComputedStyle(element, null)).height);
/*兼容写法*/
getPropertyValue方法
getPropertyValue方法可以获取CSS样式申明对象上的属性值(直接属性名称),例如:
window.getComputedStyle(element, null).getPropertyValue(“float”);
用getPropertyValue方法不必可以驼峰书写形式(不支持驼峰写法),例如:style.getPropertyValue(“border-top-left-radius”);
兼容性
getPropertyValue方法IE9+以及其他现代浏览器都支持,对于IE6-8有另外一套方案
getAttribute
在老的IE浏览器(包括最新的),getAttribute方法提供了与getPropertyValue方法类似的功能,可以访问CSS样式对象的属性。用法与getPropertyValue类似:style.getAttribute(“float”);
使用getAttribute方法也不需要cssFloat与styleFloat的怪异写法与兼容性处理。不过,还是有一点差异的,就是属性名需要驼峰写法,如下:style.getAttribute(“backgroundColor”);
如果不考虑IE6浏览器,也是可以这么写:style.getAttribute(“background-color”);
getPropertyCSSValue
getPropertyCSSValue方法返回一个CSS最初值(CSSPrimitiveValue)对象(width, height, left, …)或CSS值列表(CSSValueList)对象(backgroundColor, fontSize, …),这取决于style属性值的类型。在某些特别的style属性下,其返回的是自定义对象。该自定义对象继承于CSSValue对象(就是上面所说的getComputedStyle以及currentStyle返回对象)。
getPropertyCSSValue方法兼容性不好,IE9浏览器不支持,Opera浏览器也不支持(实际支持,只是老是抛出异常)。而且,虽然FireFox中,style对象支持getPropertyCSSValue方法,但总是返回null. 因此,目前来讲,getPropertyCSSValue方法可以先不闻不问。