抚州市网站建设_网站建设公司_测试上线_seo优化
2025/12/20 14:09:59 网站建设 项目流程

jQuery UI AddClass(添加 Class)特效实例

addClass()是 jQuery UI Effects 核心的一部分,它可以以动画效果平滑添加 CSS 类,而不是瞬间改变样式。常用于高亮提示、状态切换、颜色渐变、尺寸变化等交互反馈,比普通.addClass()更生动。

它支持持续时间、easing 缓动函数和回调,与removeClass()toggleClass()switchClass()类似。

官方文档:https://jqueryui.com/addClass/

下面提供几个渐进实例,代码使用最新 CDN,可直接复制到 HTML 文件测试。

1.基础添加 Class 动画

点击按钮平滑添加类,实现颜色和大小变化。

<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>jQuery UI AddClass 示例</title><linkrel="stylesheet"href="//code.jquery.com/ui/1.13.2/themes/smoothness/jquery-ui.css"><scriptsrc="//code.jquery.com/jquery-3.6.0.min.js"></script><scriptsrc="//code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script><style>.highlight{background:#ffeb3b;color:#d32f2f;font-size:1.5em;padding:20px;border-radius:10px;}#box{width:150px;height:100px;background:#4CAF50;color:white;text-align:center;line-height:100px;margin:20px;transition:none;/* 避免浏览器默认过渡干扰 */}</style></head><body><buttonid="add">添加高亮效果</button><buttonid="remove">移除高亮</button><divid="box">点击按钮添加动画效果</div><script>$(function(){$("#add").click(function(){$("#box").addClass("highlight",1000);// 1秒内平滑添加类});$("#remove").click(function(){$("#box").removeClass("highlight",1000);// 平滑移除});});</script></body></html>
2.使用 easing 缓动 + 回调

添加缓动效果,让动画更自然。

<style>.success{background:#4CAF50;transform:scale(1.2);box-shadow:0 0 20pxrgba(0,255,0,0.6);}</style><buttonid="success">成功反馈</button><script>$("#success").click(function(){$("#box").addClass("success",1500,"easeOutBounce",function(){alert("操作成功!");// 3秒后自动移除setTimeout(function(){$("#box").removeClass("success",1000);},3000);});});</script>

注意:easeOutBounce等高级缓动需 jQuery UI 自带(已包含),无需额外引入。

3.多个类同时添加 + switchClass

从一个状态平滑切换到另一个状态。

<style>.normal{background:#2196F3;font-size:1em;}.warning{background:#FF9800;font-size:1.3em;}.error{background:#f44336;font-size:1.6em;font-weight:bold;}</style><buttonid="warn">警告状态</button><buttonid="err">错误状态</button><buttonid="reset">恢复正常</button><script>$("#warn").click(function(){$("#box").switchClass("normal","warning",1000);});$("#err").click(function(){$("#box").switchClass("normal","error",1000);});$("#reset").click(function(){$("#box").switchClass("warning error","normal",1000);});</script>
4.toggleClass 切换类动画

点击同一个按钮切换状态。

<style>.active{background:#9C27B0;color:white;transform:rotate(360deg)scale(1.1);}</style><divid="toggleBox"style="width:200px;height:100px;background:#ccc;margin:20px;text-align:center;line-height:100px;">点击我切换状态</div><script>$("#toggleBox").click(function(){$(this).toggleClass("active",800);});</script>

小技巧

  • 所有可动画的 CSS 属性都会平滑过渡(如 color、background-color、font-size、width、height、opacity、transform 等)。
  • 推荐在目标类中定义可动画属性,避免使用transition导致双重动画。
  • 队列管理:多个 addClass 会排队执行,形成连续动画。

addClass() 动画是提升用户体验的绝佳方式,常用于按钮点击反馈、表单验证高亮、状态指示灯等。如果你需要表单错误字段高亮列表项选中动画,或结合 Effect 的复合动画示例,请告诉我!

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询