天天看点

获取元素CSS值getComputedStyle()

一、getComputedStyle是what?

话说我最近正在看原生代码的时候,碰到了个眼熟的(我最近眼热,看碎都是熟的),虽说知道他的用法和功能,但是一直没有往深处了解下,所以就到标准上看了下简介

This method is used to get the computed style as it is defined in [CSS2]

           

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

The Window.getComputedStyle() method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain.
           

其语法如下:

var style = window.getComputedStyle(element[, pseudoElt]);
           

第一个参数是必须是element对象(如果不是element节点,将会抛出错误),且不可省略。第二个参数虽说可以省略,但为了兼容性,在不是伪类的情况下建议设置为null

getComputedStyle 返回的对象跟 element 调用 style 属性返回的对象是同一种类型,都为 CSSStyleDeclaration对象。但是这两者有着不同的用处,getComputedStyle 返回的是只读对象,用于检测元素的样式,而style则是可读可写,用于设置元素上的样式;第二个不同之处就在于getComputedStyle()会将最终应用在元素上的所有CSS属性对象都读取出来(无论有米有应用到该css样式),style则只能获取元素style属性中的CSS样式。

二、浏览器兼容

获取元素CSS值getComputedStyle()

三、getDefaultComputedStyle()方法

getDefaultComputedStyle()方法是非标准的,目前是只有火狐浏览器支持,不过他的功能和调用语法和getComputedStyle()方法大致是一样一样的

var style = window.getDefaultComputedStyle(element[, pseudoElt]);
           

四、currentStyle

目前支持currentStyle()方法的只有IE浏览器(Opera浏览器为Presto内核时支持该方法,最新版本的Opera浏览器是WebKit内核,已经不支持该方法)返回的是元素当前应用的最终CSS属性值(包括外链CSS文件,以及style中的属性等)。

获取一个元素的所有最终使用的CSS属性值兼容性方法:

五、getPropertyValue()与getAttribute()

getPropertyValue(): 获取CSS样式上指定的属性值。

语法为:

window.getComputedStyle(element, null).getPropertyValue('float')
           

如果不使用该方法获取属性值,也可以直接键值访问。

but…………

有些浏览器访问同一属性但键值不同就得判断下浏览器,有些属性(比如马margin-top)需要书写驼峰形式,直接使用getPropertyValue()则可不必这样麻烦(我是懒人一枚……)。

浏览器兼容性:

获取元素CSS值getComputedStyle()

getAttribute(): 与getPropertyValue()类似的功能,获取CSS样式对象上指定的属性(该方法是针对ie下的)。

总结:

虽然现在的js库很多也很优秀,在平时的工作中有这些库就可以火力全开了,不过私下里还是多了解熟悉下底层的js技术,毕竟自己理解的才能变成自己的知识库,地基牢固才有立足的根本。

https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

https://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSview-getComputedStyle

https://developer.mozilla.org/en-US/docs/Web/API/Window/getDefaultComputedStyle

继续阅读