第一种: 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.