JavaScript获取、修改CSS样式合辑

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #box{
            height: 200px;
            width: 200px;
            color: white;
            background-color: orange;
        }
    </style>
</head>
<body>
    <div style="text-align:center;" id="box">
        <span style="font-size:20px;" id="txt">测试样例哈</span>
    </div>
    <script>
        var box = document.getElementById("box");
        var txt = document.getElementById("txt");
        //1 .style.property 仅能获取内联样式 但可以修改样式
        console.log(box.style.textAlign);//center
        console.log(box.style.color);//空白
        // box.style.color = "black";//√
        //不可加!important

        //2 .style.cssText
        console.log(box.style.cssText);//text-align:center, 返回
        // txt.style.cssText = "color:red;";//注意,会覆盖之前的样式,包括在这里没有写到的,相当于清除了原本元素的样式
        //但是继承而来的样式不会被清除,如这里继承自box的居中对齐
        //可加!important,如用来覆盖继承的属性

        //3 .style.setProperty
        txt.style.setProperty("font-size","30px");//
        //仅可用于部分常用属性

        //4 document.defaultView(window).getComputedStyle
        //IE则是currentStyle[attr]
        var declaration =  document.defaultView.getComputedStyle(box,null);
        var detailStyle =  document.defaultView.getComputedStyle(box,null).height;
        // var declaration =  document.defaultView.getComputedStyle(box,null)[height];//同理
        var windowDeclaration = window.getComputedStyle(box,null);
        console.log(declaration,windowDeclaration,detailStyle);

        //4.sp 封装一个具有兼容性的属性查阅函数
        function styleCheck (element,prop,state){
            if(document.defaultView.getComputedStyle(element,state)){
                result = document.defaultView.getComputedStyle(element,state)[prop];//不能.prop哈,记得
            }else{
                result = element.currentStyle.prop;
            }
            console.log("The value of property"+ prop + " is" + " " + result + ".");
            return result;
        }
        styleCheck(box,"height");

        //5. 对样式表下手 insertRule 与 addRule
        // var changedStyleSheet = document.styleSheet[0].insertRule("#box","height","400px"); 插入新规则
    </script>
</body>
</html>