Home  >  Article  >  Web Front-end  >  getComputedStyle与currentStyle获取样式(style/class)_javascript技巧

getComputedStyle与currentStyle获取样式(style/class)_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:40:01969browse

大家都知道,用document.getElementById(‘element').style.xxx可以获取元素的样式信息,可是它获取的只是DOM元素style属性里的样式规则,对于通过class属性引用的外部样式表,就拿不到我们要的信息了。

DOM标准里有个全局方法getComputedStyle,可以获取到当前对象样式规则信息,如:getComputedStyle(obj,null).paddingLeft,就能获取到对象的左内边距。但是事情还没完,万恶的IE不支持此方法,它有自己的一个实现方式,那就是currentStyle,不同于全局方法getComputedStyle,它是作为DOM元素属性存在的,如:obj.currentStyle.paddingLeft,在IE中就获取到对象的左内边距了,兼容性的写法如下:

复制代码 代码如下:

return window.getComputedStyle ? window.getComputedStyle(obj,null).paddingLeft : obj.currentStyle.paddingLeft;

这样,就能在IE及FF中返回对象的当前样式信息了。

特别注意一点:如果要获取当前对象的颜色信息,IE返回的是16进制的'#ffffff',而FF返回的是rgb(255,255,255)

用js的style属性可以获得html标签的样式,但是不能获取非行间样式。那么怎么用js获取css的非行间样式呢?在IE下可以用currentStyle,而在火狐下面我们需要用到getComputedStyle。下面是一个小示例:
复制代码 代码如下:




js用currentStyle和getComputedStyle获取css样式







Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn