jQuery的addClass()主要用于向选中的元素添加一个或多个CSS类,可以链式调用,并且不会移除已有的类。同时,jQuery UI扩展了这个方法,支持动画效果,比如持续时间、缓动函数等。
使用场景
动态修改样式
在用户交互(如点击、悬停)或条件满足时,动态为元素添加 CSS 类以改变样式(如颜色、布局、动画)。
表单验证
当表单输入无效时,添加错误类(如 .error)以高亮错误字段。
状态切换
根据元素的状态(如激活、禁用)添加对应类(如 .active、.disabled)。
动画过渡
结合 jQuery UI 实现平滑的动画效果(如淡入、缩放)。
一、添加单个类
<!DOCTYPE html><html><head><style>.highlight {background-color: yellow;font-weight: bold;}</style><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script></head><body><p>点击按钮高亮此段落。</p><button>高亮</button><script>$(document).ready(function() {$("button").click(function() {$("p").addClass("highlight");});});</script></body></html>
二、 添加多个类
// 添加多个类(用空格分隔)$("p").addClass("highlight bold-text");
三、动态生成类名
// 使用函数动态返回类名$("p").addClass(function(index, currentClass) {return index % 2 === 0 ? "even" : "odd";});
四、带动画的类添加
<!DOCTYPE html><html><head><style>.big-blue {width: 200px;height: 200px;background-color: #00f;}</style><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script><script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script></head><body><div style="width: 100px; height: 100px; background-color: #ccc;"></div><button>放大并变色</button><script>$(document).ready(function() {$("button").click(function() {$("div").addClass("big-blue", 1000, "easeOutBounce", function() {alert("动画完成!");});});});</script></body></html>
五、动态类名与动画结合
// 根据索引动态添加类并动画
$("li").each(function(index) {$(this).addClass("item-" + index, 500, "swing");
});
六、注意事项
依赖库
基础 addClass() 仅需 jQuery。
动画功能需引入 jQuery UI 库。
性能优化
避免频繁操作 DOM,尽量批量添加类。
使用 queue: false 可跳过动画队列(如需立即执行)。
CSS 冲突
确保添加的类样式不会与其他类冲突,优先使用 !important 或更高特异性选择器。