×

应用JS给元素中添加和删除多个class类

作者:andy0012019.11.21来源:Web前端之家浏览:7640评论:0
关键词:js

想要使用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>

示例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>

您的支持是我们创作的动力!
温馨提示:本文作者系 ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/js2349023949324.html

网友评论文明上网理性发言 已有0人参与

发表评论: