对于css样式的获取问题,对于行内样式,咱们能够用style来获取,可是对于内嵌和外部样式的话,style就心有余和力不足了。它是获取不到这些样式的javascript
此时就只有currentStyle和getComputedStyle上阵了。css
currentStyle是只兼容各类IE的,可是不兼容火狐,谷歌的,而getComputeStyle的话是能够兼容火狐,谷歌,和IE9+的。(如下测试均在谷歌和IE下)html
对于行内样式:java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <!-- <link href="test.css" rel="stylesheet"> --> <script type="text/javascript" src="test.js" defer="defer"></script> <title>Document</title> </head> <style type="text/css"> </style> <body> <div class="wrap" style=" width:100px; height:100px; background-color:black;"> </div> </body> </html>
此时用这着三种方法:浏览器
var oWrap = document.getElementsByTagName("div")[0]; window.onload = function (){ console.log(oWrap.style.width); console.log(oWrap.currentStyle.width); console.log(getComputedStyle(oWrap,null).width); }
获得的结果是:测试
把报错的,也就是currentStyle注释掉,就会获得:spa
情理之中。由于currentStyle时不兼容谷歌的code
而后改为内嵌样式的话:htm
结果也在乎料之中:blog
再加上注释了,结果是:
外部样式表的话,结果也是同样的。
而后IE的话,
IE8的话是不支持getComputedStyle。而IE9+是支持的。
外部样式IE8:
外部样式IE9:
最后彻底符合结果。
结论:
1.style只支持行内样式,对于其余样式引入方式一概很差用。
2.currentStyle和getComputedStyle支持各类样式引入方式。但存在兼容性问题。
3.currentStyle兼容IE,不兼容谷歌,火狐等浏览器,会报错。
4.getComputedStyle兼容谷歌,火狐,IE9+,不兼容IE8如下,包括IE8。
注意:
1.currentStyle的使用方式是:元素.currentStyle("样式名")或者元素.currentStyle.样式名。
2.getComputedStyle是全局的,使用方式是:getComputedStyle("元素",“伪类”)["样式名"]或者getComputedStyle("元素",“伪类”).样式名。