jquery怎么添加类和移除类

青灯夜游
青灯夜游 原创
2022-11-22 19:24:31 1020浏览

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

本教程操作环境: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>

1.gif

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>

2.gif

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

以上就是jquery怎么添加类和移除类的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。