
className 属性用于更改元素的类。在这里,我们将看到两个例子 -
在此示例中,我们将使用 className 属性更改元素的类。假设我们有一个带有 oldStyle 类的 div -
<div id="mydiv" class="oldStyle"> <p>The div...</p> </div>
我们将使用 className 属性将上面的 oldStyle 类设置为一个新类,即 newStyle -
立即学习“Java免费学习笔记(深入)”;
function demoFunction() {
document.getElementById("mydiv").className = "newStyle";
}
我们通过单击以下按钮调用 demoFunction() 实现了上述目标 -
<p>Click the below button to change the class</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/xiazai/code/10131">
<img src="https://img.php.cn/upload/webcode/000/000/004/176088420393879.jpg" alt="瑞克商易仿淘宝多用户商城">
</a>
<div class="aritcle_card_info">
<a href="/xiazai/code/10131">瑞克商易仿淘宝多用户商城</a>
<p>v4.5更新说明:修改店铺自定义分类为一级重新整合bbsxp论坛,修正了一致的所有错误。如分页,搜索,通行密码,选项等错误修改添加会员认证功能。认证后可以再次升级认证.增加虚拟币使用功能。可使用虚拟币购买收费店铺时间,站长可以在后台控制价格。订单管理中添加付款连接,使买家下订单后可以选择是否马上付款。增加首页两侧广告条增加在后台可以更改9大主题的名称增加修改后台的求购管理增加会员申请收费店铺及收费</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="瑞克商易仿淘宝多用户商城">
<span>0</span>
</div>
</div>
<a href="/xiazai/code/10131" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="瑞克商易仿淘宝多用户商城">
</a>
</div>
<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速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
C++高性能并发应用_C++如何开发性能关键应用
Java AI集成Deep Java Library_Java怎么集成AI模型部署
Golang后端API开发_Golang如何高效开发后端和API
Python异步并发改进_Python异步编程有哪些新改进
C++系统编程内存管理_C++系统编程怎么与Rust竞争内存安全
Java GraalVM原生镜像构建_Java怎么用GraalVM构建高效原生镜像
Python FastAPI异步API开发_Python怎么用FastAPI构建异步API
C++现代C++20/23/26特性_现代C++有哪些新标准特性如modules和coroutines
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号