好哇网

JavaScript给某个div增加class 样式(三种方式)

作者 2021-05-4 486

第一种: el.setAttribute(‘class’,’abc’);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE HTML>
    <HTML>
    <HEAD>
    <meta charset="utf-8" />
    <title>setAttribute('class', 'abc')</title>
    <style type="text/css">
    .abc {
    background: red;
    }
    </style>
    </HEAD>
    <BODY>
    <div id="div">test div</div>
    <script>
    var div = document.getElementById('div');
    div.setAttribute("class", "abc");
    </script>
    </BODY>
    </HTML>

第二种: el.setAttribute(‘className’, ‘abc’);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE HTML>
    <HTML>
    <HEAD>
    <meta charset="utf-8" />
    <title>setAttribute('className', 'abc')</title>
    <style type="text/css">
    .abc {
    background: red;
    }
    </style>
    </HEAD>
    <BODY>
    <div id="div">test div</div>
    <script>
    var div = document.getElementById('div');
    div.setAttribute("className", "abc");
    </script>
    </BODY>
    </HTML>

第三种:el.className = ‘abc’;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE HTML>
    <HTML>
    <HEAD>
    <meta charset="utf-8" />
    <title>el.className = 'abc'</title>
    <style type="text/css">
    .abc {
    background: red;
    }
    </style>
    </HEAD>
    <BODY>
    <div id="div">test div</div>
    <script>
    var div = document.getElementById('div');
    div.className = 'abc';
    </script>
    </BODY>
    </HTML>

建议使用第三种方法, 其他方法可能存在浏览器兼容问题。

测试运行:

Tips:You can change the code before run.

发表评论

好哇网,每天提供1000+次下载,做你身边靠谱的下载站!

立刻探索下载

留言咨询