js div.style.无法访问css类

js以这种方式去访问CSS样式无法达到效果,原因:CSS数据并非存储在style属性中,而是存储在类中。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>样式属性和方法</title>
    <style>
        #div1{
            width: 100px;
            height: 100px;
            border:1px solid black;
            background: red;
        }
    </style>
</head>
<body>
<div id="div1" style="width: 100px;">

</div>
<script>
        var supportDOOM2CSS=document.implementation.hasFeature("CSS","2.0");
        var supportDOOM2CSS1=document.implementation.hasFeature("CSS2","2.0");
        document.write(supportDOOM2CSS+" "+supportDOOM2CSS1);
        var oDiv=document.getElementById("div1");
        alert(oDiv.style.backgroundColor);

</script>
</body>
</html>



但是"DOM2级样式"增强了document.defaultView,提供了getComputedStyle()方法。我们就可以获取样式表中的信息(只能访问,不能修改):
例:
        var oDiv=document.getElementById("div1");
        var computedStyle=document.defaultView.getComputedStyle(oDiv,null);
        alert(computedStyle.width);
        alert(computedStyle.border);
IE中并不能输出border的信息,因为这是一个综合属性;
IE11版本也支持getComputedStyle()方法,但是我们也可以用currentStyle()方法来返回样式;
例:
var computedStyle=oDiv.currentStyle;
alert(computedStyle.width);
css样式规则可以访问和修改样式:
例:
        var sheet=document.styleSheets[0];
        var rules=sheet.rules || sheet.cssRules;
        var rule=rules[0];
        alert(rule.selectorText);
        alert(rule.style.cssText);
        alert(rule.style.width);

//        修改样式信息
        rule.style.width="200px";
        rule.style.height="200px";



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值