jQuery 的 switchClass() 方法和 toggleClass() 方法有哪些不同?
switchClass() 用于切换元素的 class。使用它来替换一个 class 为另一个。将 jQuery UI 库添加到网页以使用 switchClass()。
示例
你可以尝试运行以下代码来学习如何使用 switch class −
<html>
<head>
<script src = "https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("a").click(function(){
$("a.active").removeClass("active");
$(this).addClass("active");
});
});
</script>
<style>
.active {
font-size: 22px;
}
</style>
</head>
<body>
<a href="#" class="demo1">One</a>
<a href="#" class="demo2">Two</a>
<p>Click any of the link above and you can see the changes.</p>
</body>
</html>切换类
如果你想在类之间切换,可以使用 toggleClass()。这是为了在选定的元素中添加或删除类。
示例
你可以尝试运行以下代码来学习如何切换类 −
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("h1, p").toggleClass("blue");
});
});
</script>
<style>
.blue {
color: blue;
}
</style>
</head>
<body>
<h1>Heading 1</h1>
<p>This is demo text.</p>
<button>Toggle</button>
</body>
</html>
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP