将switchClass()用于从一个元件切换类。用它来将一个类替换为另一个类。将jQuery UI库添加到网页以使用switchClass()。
您可以尝试运行以下代码来学习如何使用switch类-
<html>
<head>
<script src = "https://cdn.staticfile.org/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://cdn.staticfile.org/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>