className 属性用于更改元素的类。在这里,我们将看到两个例子 -
- 如何使用 className 属性更改元素的类。
- 如何在新旧课程之间切换。
使用 className 属性更改元素的类
在此示例中,我们将使用 className 属性更改元素的类。假设我们有一个带有 oldStyle 类的 div -
<div id="mydiv" class="oldStyle"> <p>The div...</p> </div>
我们将使用 className 属性将上面的 oldStyle 类设置为一个新类,即 newStyle -
function demoFunction() { document.getElementById("mydiv").className = "newStyle"; }
我们通过单击以下按钮调用 demoFunction() 实现了上述目标 -
<p>Click the below button to change the class</p> <button onclick="demoFunction()">Change Class</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>
以上就是如何使用 JavaScript 更改元素的类?的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。