jQuery UI ToggleClass(切换 Class)特效实例
toggleClass() 是 jQuery UI Effects 中非常实用的方法,它可以以动画效果在添加和移除 CSS 类之间切换。如果元素已有该类,则平滑移除;如果没有,则平滑添加。常用于按钮激活状态、选中高亮、折叠面板开关、主题切换、表单字段焦点等交互反馈。
它支持持续时间、easing 缓动函数和回调函数,比普通 .toggleClass() 更富有动态感。
官方文档:https://jqueryui.com/toggleClass/
下面提供几个渐进实例,代码使用最新 CDN,可直接复制到 HTML 文件测试。
1. 基础切换 Class 动画
点击元素自身切换状态。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery UI ToggleClass 示例</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="//code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
<style>
.active {
background: #2196F3;
color: white;
font-size: 1.6em;
padding: 30px;
border-radius: 12px;
box-shadow: 0 10px 25px rgba(33,150,243,0.4);
transform: scale(1.1) rotate(2deg);
}
#box {
width: 200px;
height: 120px;
background: #795548;
color: white;
text-align: center;
line-height: 120px;
margin: 40px auto;
cursor: pointer;
border-radius: 8px;
}
</style>
</head>
<body>
<div id="box">点击我切换状态</div>
<script>
$(function() {
$("#box").click(function() {
$(this).toggleClass("active", 1000); // 1秒内切换类
});
});
</script>
</body>
</html>
2. 按钮控制切换 + 缓动效果
使用独立按钮控制,并添加弹跳缓动。
<button id="toggleBtn">切换状态</button>
<style>
.success {
background: #4CAF50;
color: white;
transform: scale(1.15);
box-shadow: 0 0 30px rgba(76,175,80,0.6);
}
</style>
<script>
$("#toggleBtn").click(function() {
$("#box").toggleClass("success", 1200, "easeOutBounce");
});
</script>
3. 多个类同时切换 + 回调
切换多个类,并在动画结束后提示。
<style>
.selected { background: #FF9800; font-weight: bold; }
.enlarged { font-size: 2em; transform: rotate(-5deg); }
</style>
<button id="multiToggle">切换选中+放大</button>
<script>
$("#multiToggle").click(function() {
$("#box").toggleClass("selected enlarged", 1500, function() {
var hasClass = $(this).hasClass("selected");
alert(hasClass ? "已激活多重状态!" : "已恢复默认");
});
});
</script>
4. 常见应用:折叠面板开关按钮
结合图标,实现“展开/收起”按钮效果。
<button id="collapseBtn" class="ui-button">
<span class="ui-icon ui-icon-triangle-1-s"></span> 展开详情
</button>
<div id="content" style="display:none; padding:20px; background:#eee;">
这里是隐藏的详细内容...
</div>
<style>
.open { transform: rotate(180deg); }
</style>
<script>
$("#collapseBtn").click(function() {
$("#content").slideToggle(800); // 内容滑动显示/隐藏
$(this).toggleClass("open", 600); // 箭头旋转动画
$(this).find("span").toggleClass("ui-icon-triangle-1-s ui-icon-triangle-1-n", 600);
$(this).text(function(i, text) {
return text.includes("展开") ? "收起详情" : "展开详情";
});
});
</script>
小技巧:
- 可动画属性:所有数值型 CSS(如 color、background、width、font-size、opacity、transform、box-shadow 等)都会平滑过渡。
- 队列动画:连续多次 toggleClass 会自动排队,形成连续效果。
- 与其他 Effects 结合:如先
.effect("shake")再 toggleClass 实现错误提示。 - 性能:避免在大量元素上同时使用复杂动画。
toggleClass() 是实现交互状态切换的最佳方式之一,常用于导航高亮、列表选中、模式切换(暗黑/明亮主题)等。如果你需要 暗黑模式切换、列表多选高亮、或 表单字段错误/正确状态动画 的完整示例,请告诉我!