原文 张鑫旭 http://www.zhangxinxu.com/wordpress/2012/05/getcomputedstyle-js-getpropertyvalue-currentstyle/
二、getComputedStyle是?
getComputedStyle是一个可以获取当前元素所有最终使用的CSS属性值。返回的是一个CSS样式声明对象([object CSSStyleDeclaration]),只读。
getComputedStyle()gives the final used values of all the CSS properties of an element.
语法如下:
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的区别
我们使用element.style也可以获取元素的CSS样式声明对象,但是其与getComputedStyle方法还有有一些差异的。
- 只读与可写
正如上面提到的getComputedStyle方法是只读的,只能获取样式,不能设置;而element.style能读能写,能屈能伸。 - 获取的对象范围
getComputedStyle方法获取的是最终应用在元素上的所有CSS属性对象(即使没有CSS代码,也会把默认的祖宗八代都显示出来);而element.style只能获取元素style属性中的CSS样式。因此对于一个光秃秃的元素<p>,getComputedStyle方法返回对象中length属性值(如果有)就是190+(据我测试FF:192, IE9:195, Chrome:253, 不同环境结果可能有差异), 而element.style就是0。
四、getComputedStyle与defaultView
如果我们查看jQuery源代码,会发现,其css()方法实现不是使用的window.getComputedStyle而是document.defaultView.getComputedStyle,唷?这是怎么一回事?
实际上,使用defaultView基本上是没有必要的,getComputedStyle本身就存在window对象之中。根据DennisHall的说法,使用defaultView可能一是人们不太乐意在window上专门写个东西,二是让API在Java中也可用(这我不懂,忘指点~~)。
不过有个特殊情况,在FireFox3.6上不使用defaultView方法就搞不定的,就是访问框架(frame)的样式.
五、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()方法无法体现的一点。
//zxx: 如果你只知jQuery css()方法,你是不会知道伪类样式也是可以获取的,虽然部分浏览器不支持。
例如,我们要获取一个元素的高度,可以类似下面的代码:
alert((element.currentStyle? element.currentStyle : window.getComputedStyle(element, null)).height);
本文详细介绍了getComputedStyle方法,探讨了它与element.style及IE特有的currentStyle属性的区别。此外,还讲解了getComputedStyle方法的语法、用途及其与jQuery的关系。


2万+

被折叠的 条评论
为什么被折叠?



