如何使用 JavaScript 更改元素的类?

javascriptweb developmentfront end technology

className 属性用于更改元素的类。在这里,我们将看到两个示例 -

  • 如何使用 className 属性更改元素的类。
  • 如何在旧类和新类之间切换。

使用 className 属性更改元素的类

在此示例中,我们将使用 className 属性更改元素的类。假设我们有一个带有类 oldStyle 的 div -

<div id="mydiv" class="oldStyle">
<p>div...</p>
</div>

我们将使用 className 属性将上述 oldStyle 类设置为新类,即 newStyle −

function demoFunction() {
    document.getElementById("mydiv").className = "newStyle";
}

我们通过单击以下按钮调用 demoFunction() 实现了上述操作 −

<p>单击以下按钮更改类</p>
<button onclick="demoFunction()">更改类</button>

示例

让我们看看完整的示例 −

<!DOCTYPE html> <html> <style> .oldStyle { background-color: yellow; padding: 5px; border: 2px solid orange; font-size: 15px; } .newStyle { background-color: green; text-align: center; font-size: 25px; padding: 7px; } </style> <body> <h1>Changing the class</h1> <p>Click the below button to change the class</p> <button onclick="demoFunction()">Change Class</button> <div id="mydiv" class="oldStyle"> <p>The div...</p> </div> <script> function demoFunction() { document.getElementById("mydiv").className = "newStyle"; } </script> </body> </html>

在新旧类之间切换

示例

我们还可以创建一个双向按钮,即切换。再次单击按钮将切换回原样 −

<!DOCTYPE html> <html> <style> .oldStyle { background-color: yellow; padding: 5px; border: 2px solid orange; font-size: 15px; } .newStyle { background-color: green; text-align: center; font-size: 25px; padding: 7px; } </style> <body> <h1>Toggle the class</h1> <p>Click the below button to toggle the classes</p> <button onclick="demoFunction()">Toggle Class</button> <div id="mydiv" class="oldStyle"> <p>The div...</p> </div> <script> function demoFunction() { const element = document.getElementById("mydiv"); if (element.className == "oldStyle") { element.className = "newStyle"; } else { element.className = "oldStyle"; } } </script> </body> </html>

相关文章