JavaScript window.getComputedStyle()

 

一、window.getComputedStyle()

 

getComputedStyle 是一个可以获取当前元素所有最终使用的 CSS 属性值。返回的是一个 CSS 样式声明对象 ([object CSSStyleDeclaration]),只读。

 

 

二、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

 

 

三、window.getComputedStyle 与 document.defaultView.getComputedStyle

 

jQuery 源代码,其 css() 方法实现不是使用的 window.getComputedStyle 而是 document.defaultView.getComputedStyle,其实是等价的,但是有一点,在 FireFox3.6 上只能使用 defaultView 方法搞定框架(frame)样式。

 

 

四、getComputedStyle 与 currentStyle

 

getComputedStyle 并不支持 IE6 ~ IE8,所以需要使用 currentStyle 兼容 IE 浏览器。所以想获取一个元素的高度,可以这样写:

element.currentStyle? element.currentStyle : window.getComputedStyle(element, null)).height

 

 

五、getPropertyValue 方法与 getAttribute 方法

 

getPropertyValue方法可以获取 CSS 样式申明对象上的属性值(直接属性名称):

window.getComputedStyle(element, null).getPropertyValue("float");

如果我们不使用 getPropertyValue 方法,直接使用键值访问,也是可以的。但是,比如这里的的float,如果使用键值访问,就要写成 cssFloat 与 styleFloat,自然需要浏览器判断了,比较麻烦!

getPropertyValue 方法同样不支持 IE6 ~ IE8,所以西需要使用 getAttribute 兼容 IE 浏览器(需要驼峰写法)。

 

 

六、总结

 

最终,想要使用 getComputedStyle 方法获取元素的属性的兼容性写法:

 

var oStyle = this.currentStyle? this.currentStyle : window.getComputedStyle(this, null);
        if (oStyle.getPropertyValue) {
            alert("getPropertyValue下背景色:" + oStyle.getPropertyValue("background-color"));
        } else {
            alert("getAttribute下背景色:" + oStyle.getAttribute("backgroundColor"));
        }

 

 

参考:http://www.zhangxinxu.com/wordpress/?p=2378

 

posted @ 2016-10-05 15:37  小车厂  阅读(431)  评论(0编辑  收藏  举报