第一种: el.setAttribute('class','abc');
<!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');
<!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';
<!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>
建议使用第三种方法, 其他方法可能存在浏览器兼容问题。
原文:https://blog.csdn.net/yan791124465/article/details/71123664
评论(0)