如何使用 JavaScript 将一个类名添加到元素?
要使用 JavaScript 将一个类名添加到元素,代码如下 -
实例
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> .newStyle { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; width: 100%; padding: 25px; background-color: rgb(147, 80, 255); color: white; font-size: 25px; box-sizing: border-box; text-align: center; } </style> </head> <body> <h1>Adding className with JavaScript Example</h1> <button class="btn">Click here</button> <h2>Click the above button to add className to below div</h2> <div id="sampleDiv"> This is a DIV element. </div> <script> document.querySelector(".btn").addEventListener("click", addClassName); function addClassName() { var element = document.getElementById("sampleDiv"); element.classList.add("newStyle"); } </script> </body> </html>
输出
以上代码将产生以下输出 -
单击“单击此处”按钮 -
广告