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

给定一个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

以上就是如何使用jQuery向元素中添加和删除多个class类?的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » jQuery 答疑