HTML DOM-->内部样式表与外部样式表的读写

1.获取

  IE中:

    元素节点.currentStyle.样式属性表

    元素节点.currentStyle['样式属性名']

  其他:

    window.getComputedStyle(元素节点,伪类).样式属性名

    window.getComputedStyle(元素节点,伪类)['样式属性名']

    伪类一般写null即可

  举例:点击按钮获取它的背景色

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>js_excise</title>
        <script src="./js/js_excise.js" type="text/javascript" charset="utf-8"></script>
    </head>
    <body style="height: 187.5rem;">
        <button id="in" onclick="func()" style="background-color: red;">更新</button>
        <input  type="text" name="Text" placeholder="please your name" my='abner'>
        <script type="text/javascript">
            var w = document.getElementById('in')
            function func(){
                var c = window.getComputedStyle(w,null).backgroundColor
                console.log(c)
            }
        </script>
    </body>
</html>

  输出:

 2.设置样式中属性的值

  元素节点.Style.样式属性名 = 样式属性值

  举例:将按钮颜色改为绿色

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>js_excise</title>
        <script src="./js/js_excise.js" type="text/javascript" charset="utf-8"></script>
    </head>
    <body style="height: 187.5rem;">
        <button id="in" onclick="func()" style="background-color: red;">更新</button>
        <input  type="text" name="Text" placeholder="please your name" my='abner'>
        <script type="text/javascript">
            var w = document.getElementById('in')
            function func(){        
                w.style.backgroundColor = 'green'
                var c = window.getComputedStyle(w,null).backgroundColor
                console.log(c)
            }
        </script>
    </body>
</html>

  输出:

  

原文地址:https://www.cnblogs.com/abner-pan/p/12725026.html