js中获取css样式的两种方式

1. 对象.style.样式名

弊端就是只能获取行内样式

2.window.getComputedStyle(对象,null);

最好用第二种方式

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <style type="text/css">
        #box{
            width: 40px;
            height: 40px;
            background-color: red;
        }
        
    </style>
    <body>
        <button  >切换</button>
        <div ></div>
    </body>
        <script>
            var box = document.getElementById("box");
            var btn = document.getElementById("btn");
            var sty = getComputedStyle(box,null);
            btn.onclick = function(){
                console.log(box.style.background);
                if(sty.backgroundColor == "rgb(255, 0, 0)"){
                    box.style.backgroundColor = "blue";
                }else{
                    box.style.backgroundColor = "red";
                }
            }
        </script>
</html>