站长资讯网
最全最丰富的资讯网站

jquery怎么添加类和移除类

jquery中可用addClass()和removeClass()来添加类和移除类。addClass()向被选元素添加一个或多个类,语法“$(selector).addClass(类名)”,如需添加多个类,就使用空格分隔类名。removeClass()从被选元素移除一个或多个类,语法“$(selector).removeClass(类名)”;参数可以省略,此时就会清空所有类。

jquery怎么添加类和移除类

前端(vue)入门到精通课程:进入学习
Apipost = Postman + Swagger + Mock + Jmeter 超好用的API调试工具:点击使用

本教程操作环境:windows7系统、jquery3.6.1版本、Dell G3电脑。

jquery添加类和移除类的方法

方法 描述
addClass() 向匹配的元素添加指定的类名。
removeClass() 从所有匹配的元素中删除全部或者指定的类。

jquery addClass()添加类

addClass() 方法向被选元素添加一个或多个类。

该方法不会移除已存在的 class 属性,仅仅添加一个或多个 class 属性。

提示:如需添加多个类,请使用空格分隔类名。

语法:

$(selector).addClass(class)
登录后复制

参数 描述
class 必需。规定一个或多个 class 名称。

示例:向第一个 p 元素添加一个类

<!DOCTYPE html> <html> 	<head> 		<script src="js/jquery-3.6.1.min.js"></script> 		<script type="text/javascript"> 			$(document).ready(function() { 				$("button").click(function() { 					$("p:first").addClass("intro"); 				}); 			}); 		</script> 		<style type="text/css"> 			.intro { 				font-size: 120%; 				color: red; 			} 		</style> 	</head>  	<body> 		<h1>This is a heading</h1> 		<p>This is a paragraph.</p> 		<p>This is another paragraph.</p> 		<button>向第一个 p 元素添加一个类</button> 	</body> </html>
登录后复制

jquery怎么添加类和移除类

jQuery removeClass()移除类

removeClass() 方法从被选元素移除一个或多个类。

注释:如果没有规定参数,则该方法将从被选元素中删除所有类。

语法:

$(selector).removeClass(class)
登录后复制

参数 描述
class

可选。规定要移除的 class 的名称。

如需移除若干类,请使用空格来分隔类名。

如果不设置该参数,则会移除所有类。

示例:移除所有 <p> 的 "intro" 类

<!DOCTYPE html> <html> 	<head> 		<script src="js/jquery-3.6.1.min.js"></script> 		<script type="text/javascript"> 			$(document).ready(function() { 				$("button").click(function() { 					$("p").removeClass("intro"); 				}); 			}); 		</script> 		<style type="text/css"> 			.intro { 				font-size: 120%; 				color: red; 			} 		</style> 	</head>  	<body> 		<h1 id="h1">This is a heading</h1> 		<p class="intro">This is a paragraph.</p> 		<p>This is another paragraph.</p> 		<button>从第一个段落中删除类</button> 	</body> </html>
登录后复制

jquery怎么添加类和移除类

【推荐学习:jQuery视频教程、web前端视频】

赞(0)
分享到: 更多 (0)