likes
comments
collection
share

JS修改样式属性

作者站长头像
站长
· 阅读数 10

JS修改样式属性

本篇记录两个修改样式的方法,即对style进行修改

element.style(行内样式操作)

需要注意的是:在JS中修改样式属性需要采取驼峰命名法,并且这种操作方法修改的内容较少

具体例子如下所示

<head>
    <style>
        div {
            width: 200px;
            height: 200px;
            background-color: black;
        }
    </style>
</head>
<body>
    <div></div>
    <script>
        // 1. 获取元素
        var div = document.querySelector('div');
        // 2. 注册事件 处理程序
        div.onclick = function() {
   // div.style里面的属性 采取驼峰命名法  其中使用了backgroundColor而并非CSS中的background-color
            this.style.backgroundColor = 'blue';
            this.style.width = '250px';
        }
    </script>
</body>

执行结果如下所示

JS修改样式属性JS修改样式属性

element.className(类名样式操作)

这种样式操作方法可以通过修改类名从而一次性修改多种样式,一般适用于修改的样式较多的情况

具体例子如下所示

<head>
    <style>
        div {
            width: 100px;
            height: 100px;
            color:green;
            background-color: black;
        }
        
        .change {
            background-color: blue;
            color: #fff;
            font-size: 25px;
            margin-top: 100px;
        }
    </style>
</head>
<body>
    <div class="first">文本</div>
    <script>
        var test = document.querySelector('div');
        test.onclick = function() {
        	// 如果用element.style方法进行修改会十分繁琐。例如
            // this.style.backgroundColor = 'purple';
            // this.style.color = '#fff';
            // this.style.fontSize = '25px';
            // this.style.marginTop = '100px';
            

            // 因此我们可以通过 修改元素的className更改元素的样式 适合于样式较多或者功能复杂的情况
            // 如果想要保留原先的类名,我们可以这么做 多类名选择器
            this.className = 'change';
            // this.className = 'first change';
        }
    </script>
</body>

执行结果如下所示

JS修改样式属性JS修改样式属性