1,获取行内样式
js 获取行内样式可以通过元素的 style 属性得到,例如:
var demo = document.querySelector("#demo");
var color = demo.style.color;
2,获取非行内样式
通过上面的方法获取非行内样式时,得不到任何值,那么如何获取呢?
在 IE 浏览器中,元素支持 currentStyle 属性;在非 IE 浏览器中支持 getComputedStyle.
最后利用这个区别,写一个兼容的获取元素样式的函数:
function getStyle(el, attr) {
return el.currentStyle ? el.currentStyle[attr] : window.getComputedStyle(el, false)[attr];
}
3,element.style 和 currentStyle,getComputedStyle 的区别
(1)兼容性:element..style 兼容所有的浏览器;currentStyle 只在 IE 浏览器中等到支持;getComputedStyle 在非 IE 浏览器和 IE9 及以上的浏览器中都支持.
(2)使用范围:element..style 只可以获取到行内样式,currentStyle,getComputedStyle 可以获取到行内样式,内部样式和外部样式.
(3)是否获取最终样式:element.style 得到的是 style 属性里的样式,不一定是最终样式,而 currentStyle,getComputedStyle 两个得到的是元素的最终 CSS 样式.
(4)可读可写性:element.style 可读可写(即支持获取样式,也支持设置样式),currentStyle,getComputedStyle 只可读不可写(只可以用来获取样式,不可以被用来设置样式);
来源: http://www.qdfuns.com/notes/47066/81d2044038e672565e8393b8dc75e720.html