用javascript更改css样式的三种方式

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .bb{
                width: 300px;
                height: 300px;
                background: cadetblue;
            }
        </style>
    </head>
    <body>
        <div id="aa"></div>
        <script>
            //第一种:获取相应标签对应的script对象.style
            (
                function(){
                    var a = document.getElementById("aa");
                    a.style.width = "200px";
                    a.style.height = "200px";
                    a.style.backgroundColor = "chartreuse";
                }
            )();

            //第二种:获取相应标签对应的script对象.className
            var a = document.getElementsByTagName("div")[0];
            a.className = "bb";


            //第三种:获取相应标签对应的script对象.setAtribute("属性名","属性值")
            var a = document.getElementsByTagName("div")[0];
            a.setAttribute("class","bb");
            a.removeAttribute("class");
        </script>
    </body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_41135704/article/details/81515795
今日推荐