如何使用jQuery向元素中添加和删除多个class类?

本文介绍如何使用JQuery向HTML元素添加和删除多个class类,包括addClass()和removeClass()方法的使用,通过示例展示了具体操作步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定一个HTML元素,如何使用JQuery从其中添加和删除多个class类?下面本篇文章就来给大家介绍一下使用jQuery向元素中添加和删除多个class的方法,希望对大家有所帮助。

 

想要使用jQuery向HTML元素中添加和删除多个class类,首先使用jQuery选择器选择要添加多个class类的元素,然后使用addClass()方法向元素添加多个类,使用removeClass()方法删除多个类。

addClass()方法用于向被选元素添加一个或多个类;该方法不会移除已存在的 class 属性,仅仅添加一个或多个 class 属性。

removeClass()方法从被选元素移除一个或多个类;如果没有规定参数,则该方法将从被选元素中删除所有类。

示例1:使用addClass()方法将两个类color和fontWeight添加到所选元素中

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>如何添加多个类</title>
	<style> 
            .color { 
                color: red; 
            } 
            .fontWeight { 
                font-weight: bold; 
            } 
        </style>
</head>
	<body style = "text-align:center;">  
        <p id = "UP" style = "font-size: 19px;">单击按钮向元素添加多个类</p> 
        <button onClick = "Fun()">单击 </button> 
        <p id = "DOWN" style="color: green; font-size: 24px; font-weight: bold;"></p> 
        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
        <script> 
            function Fun() { 
                $("#UP").addClass("color fontWeight"); 
                $('#DOWN').text("添加了两个类color和fontweight"); 
            } 
        </script>  
    </body>  
</html>

效果图:

1.gif

示例2:使用removeClass()方法从所选元素中删除两个类color和fontWeight

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>如何删除多个类</title>
		<style> 
            .color { 
                color: red; 
            } 
            .fontWeight { 
                font-weight: bold; 
            } 
        </style>
	</head>

	<body style = "text-align:center;">  
        <p id = "UP" class="color fontWeight" style = "font-size: 19px;">单击按钮向元素添加多个类</p> 
        <button onClick = "Fun()">单击 </button> 
        <p id = "DOWN" style="color: green; font-size: 24px; font-weight: bold;"></p> 
        <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
        <script> 
            function Fun() { 
                $("#UP").removeClass("color fontWeight"); 
                $('#DOWN').text("删除两个类color和fontweight"); 
            } 
        </script>  
    </body>  
</html>

效果图:

2.gif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值