
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() 实现了上述目标 -
立即学习“Java免费学习笔记(深入)”;
<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 更改元素的类?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号