animate-spin 可快速实现旋转加载动画,但需作用于 inline 或 inline-block 元素并显式设置宽高与 border-t-transparent;可自定义速度和缓动曲线;推荐用 @apply 封装状态样式,注意顺序与兼容性。

用 animate-spin 快速实现旋转加载动画
直接加 animate-spin 类就能让元素转起来,但得注意它只对 inline 元素(比如 span)或设置了 display: inline-block 的元素生效。常见错误是套在 div 上却没设宽高,结果看不见旋转——因为默认 div 没内容、没尺寸,转了个寂寞。
实操建议:
- 优先用带语义的内联元素,比如
<span class="inline-block w-5 h-5 animate-spin border-2 border-blue-500 border-t-transparent rounded-full"></span> - 别依赖父容器撑开尺寸,显式写
w-5 h-5或类似尺寸类 -
border-t-transparent是关键:只保留单色边框的顶部透明,其他三边有颜色,才能看出旋转效果 - 避免在文字按钮里直接加
animate-spin,会把文字也转走;应该用伪元素或额外span插入图标位
自定义旋转速度与缓动曲线
Tailwind 默认的 animate-spin 是 1s 线性旋转一圈,实际项目中常需要更快、更顺或配合品牌节奏。它底层基于 @keyframes spin,所以得改配置才能调速或换缓动。
修改方式(tailwind.config.js):
立即学习“前端免费学习笔记(深入)”;
module.exports = {
theme: {
extend: {
animation: {
'spin-slow': 'spin 2s linear infinite',
'spin-ease': 'spin 0.6s cubic-bezier(0.34, 1.13, 0.66, 1.03) infinite',
}
}
}
}
之后就能用 animate-spin-slow 或 animate-spin-ease。注意:cubic-bezier 值不能写错,否则动画失效;且 Tailwind 不校验 keyframes 名是否真实存在,拼错也不会报错,只会静默不转。
用 @apply 组合动画做「加载中」按钮状态
纯 CSS 类组合容易失控,比如同时加 animate-spin 和 opacity-50 可能被覆盖。更稳的方式是在组件内用 @apply 封装完整状态样式。
例如一个禁用态加载按钮:
.btn-loading {
@apply flex items-center justify-center px-4 py-2 bg-blue-600 text-white cursor-not-allowed;
@apply animate-spin;
@apply opacity-75;
}
要点:
- 务必把
@apply animate-spin放在最后——动画类含transform,若被其他@apply覆盖会失效 - 不要在同一个元素上混用
animate-spin和animate-pulse,CSS 动画会竞争,行为不可预测 - 按钮文字需单独控制显隐,比如用
invisible而非hidden,避免布局跳动
兼容旧浏览器时的降级方案
animate-spin 依赖 transform: rotate() 和 animation,IE11 完全不支持,iOS Safari cubic-bezier 在 animation-timing-function 中支持有限。真要兼容,得手动 fallback。
做法:
- 用
@supports (animation-name: spin)包裹现代动画样式,里面写animate-spin相关规则 - 外面写降级:比如用 GIF 替代,通过
background-image加载小体积 spinner.gif - 或者用 JS 检测
CSS.supports('animation', 'spin'),动态切类名 - 别指望 Tailwind 自带 polyfill——它本身就不处理兼容性,这事得自己兜底
最常被忽略的是:动画类名在构建时被 PurgeCSS 清掉。如果只在 JS 里动态加 animate-spin,记得在 content 配置里显式写上该类名,否则生产环境消失。


















