css样式获取,style,currentStyle,getComputedStyle

 

 

 

 

对于css样式的获取问题,对于行内样式,我们可以用style来获取,但是对于内嵌和外部样式的话,style就心有余和力不足了。它是获取不到这些样式的

此时就只有currentStyle和getComputedStyle上阵了。

currentStyle是只兼容各种IE的,但是不兼容火狐,谷歌的,而getComputeStyle的话是可以兼容火狐,谷歌,和IE9+的。(以下测试均在谷歌和IE下)

对于行内样式:

<!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注释掉,就会得到:

情理之中。因为currentStyle时不兼容谷歌的

 然后改成内嵌样式的话:

结果也在意料之中:

再加上注释了,结果是:

外部样式表的话,结果也是一样的。

然后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("元素",“伪类”).样式名。

 

转载于:https://www.cnblogs.com/178-533/p/7783944.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值