Tailwind CSS 动画
系统核对 Tailwind CSS 悬停/聚焦/激活/禁用交互变体、过渡与变换动画、内置与自定义关键帧动画、交互卡片实战及无障碍降动效优化,附离线 Chromium 实测。
学完这一章,你能够
- 系统核对 Tailwind CSS 悬停/聚焦/激活/禁用交互变体、过渡与变换动画、内置与自定义关键帧动画、交互卡片实战及无障碍降动效优化,附离线 Chromium 实测。
交互状态基础与四类常用变体
交互状态指元素响应用户操作时呈现的动态外观,最常见包括悬停(`hover`)、聚焦(`focus`)、激活(`active`)与禁用(`disabled`)。Tailwind CSS 采用“变体前缀 + 工具类”的声明语法,例如在按钮上组合 `bg-blue-500`(默认蓝底)、`hover:bg-blue-700`(悬停加深)与 `focus:ring-2`(聚焦外环),即可直观表达完整状态机。
逐项细看四类状态:悬停按钮常叠加 `hover:bg-green-600 hover:shadow-md transition-all` 使色深与阴影平滑浮现;表单输入框在用 `outline-none` 移除浏览器默认虚线框时,必须以 `focus:border-blue-500 focus:ring-2 focus:ring-blue-200` 补足清晰可达的焦点反馈;按钮按压通过 `active:bg-red-700 active:scale-95` 给出即时下沉回弹;禁用按钮配 `disabled` 属性与 `cursor-not-allowed` 明确不可点击。本站使用 Playwright 在 Chromium 中执行真实悬停、聚焦、鼠标按下与禁用检测,测得悬停背景由 `rgb(34, 197, 94)` 切换至 `rgb(22, 163, 74)` 并附带阴影,聚焦输入框边框变为 `rgb(59, 130, 246)` 且产生 `2px` 蓝色外环,按压时背景变为 `rgb(185, 28, 28)` 且缩放矩阵为 `matrix(0.95, 0, 0, 0.95, 0, 0)`,禁用按钮 `disabled=true` 且光标为 `not-allowed`。
过渡动画、变换与预设/自定义关键帧
借助 Tailwind 的过渡与变换工具类,无需手写 CSS 关键帧即可打造顺滑微交互:过渡由 `transition-all`(指定过渡属性)、`duration-300`(持续 `300ms`)与 `ease-in-out`(缓动曲线)共同驱动,如 `w-20` 悬停展开到 `hover:w-40`;变换则通过 `hover:scale-105`、`active:scale-95` 实现弹性缩放。离线 Chromium 实测确认方块初始宽 `80px`、`transition-property` 为 `all`、`transition-duration` 为 `0.3s`,悬停缩放按钮的 `transform` 精确计算为 `matrix(1.05, 0, 0, 1.05, 0, 0)`。
Tailwind 内置了 `animate-spin`(旋转加载)、`animate-ping`(脉冲扩散)、`animate-pulse`(呼吸骨架屏)与 `animate-bounce`(弹跳提示)四组关键帧动画;若需自定义动效,可在 `tailwind.config.js` 的 `theme.extend.animation` 与 `keyframes` 下注册(如 `spin-slow: 'spin 3s linear infinite'` 与左右摇摆 `wiggle`)。本站实测六组动画的计算属性:`animate-spin` 为 `['spin', '1s', 'infinite']`、`animate-ping` 为 `['ping', '1s', 'infinite']`、`animate-pulse` 为 `['pulse', '2s', 'infinite']`、`animate-bounce` 为 `['bounce', '1s', 'infinite']`,自定义 `animate-spin-slow` 与 `animate-wiggle` 分别为 `['spin', '3s', 'infinite']` 与 `['wiggle', '1s', 'infinite']`。
交互式卡片实战与性能/无障碍优化
将状态变体、阴影与变换串联可构建常见的交互式卡片:外层容器设置 `shadow-lg transition-all duration-300 hover:shadow-xl hover:-translate-y-1`,鼠标移入时整体上浮 `4px`(Chromium 实测 `transform: matrix(1, 0, 0, 1, 0, -4)`)且阴影加深,内部按钮再配 `transition-colors duration-200 hover:bg-blue-700` 实现分层反馈。
为保证流畅帧率与无障碍体验,动画开发应遵循四项准则:克制页面同屏动效数量;优先对 `transform` 与 `opacity` 做动画以走合成层硬件加速、避免频繁触发布局回流与重绘;仅对确认即将频繁变换的元素谨慎添加 `will-change-transform`(实测 `will-change: transform`);同时通过 `motion-reduce:animate-none` 尊重系统减弱动态效果偏好。本站利用 Playwright 切换 `prefers-reduced-motion: reduce` 实测确认:`animate-bounce motion-reduce:animate-none` 的 `animation-name` 在默认环境下为 `bounce`,在降动效模式下自动切换为 `none`。
离线 Chromium 实测悬停/聚焦/按压/禁用变体、变换过渡、关键帧及降动效偏好
展开查看收起
"""Offline Chromium verification for Tailwind CSS animations and interaction states chapter."""
import json
from playwright.sync_api import sync_playwright
CSS = """
@keyframes spin { to { transform: rotate(360deg); } }
@keyframes ping { 75%, 100% { transform: scale(2); opacity: 0; } }
@keyframes pulse { 50% { opacity: 0.5; } }
@keyframes bounce {
0%, 100% { transform: translateY(-25%); animation-timing-function: cubic-bezier(0.8, 0, 1, 1); }
50% { transform: none; animation-timing-function: cubic-bezier(0, 0, 0.2, 1); }
}
@keyframes wiggle {
0%, 100% { transform: rotate(-3deg); }
50% { transform: rotate(3deg); }
}
.bg-blue-500 { background-color: rgb(59 130 246); }
.hover\\:bg-blue-700:hover { background-color: rgb(29 78 216); }
.bg-green-500 { background-color: rgb(34 197 94); }
.hover\\:bg-green-600:hover { background-color: rgb(22 163 74); }
.hover\\:shadow-md:hover { box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1); }
.bg-red-500 { background-color: rgb(239 68 68); }
.active\\:bg-red-700:active { background-color: rgb(185 28 28); }
.active\\:scale-95:active { transform: scale(0.95); }
.hover\\:scale-105:hover { transform: scale(1.05); }
.hover\\:-translate-y-1:hover { transform: translateY(-0.25rem); }
.border { border: 1px solid rgb(229 231 235); }
.outline-none { outline: 2px solid transparent; outline-offset: 2px; }
.focus\\:border-blue-500:focus { border-color: rgb(59 130 246); }
.focus\\:ring-2:focus { box-shadow: 0 0 0 2px rgb(191 219 254); }
.cursor-not-allowed { cursor: not-allowed; }
.w-20 { width: 5rem; }
.h-20 { height: 5rem; }
.hover\\:w-40:hover { width: 10rem; }
.transition-all { transition-property: all; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; }
.duration-300 { transition-duration: 300ms; }
.ease-in-out { transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); }
.animate-spin { animation: spin 1s linear infinite; }
.animate-ping { animation: ping 1s cubic-bezier(0, 0, 0.2, 1) infinite; }
.animate-pulse { animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite; }
.animate-bounce { animation: bounce 1s infinite; }
.animate-spin-slow { animation: spin 3s linear infinite; }
.animate-wiggle { animation: wiggle 1s ease-in-out infinite; }
.will-change-transform { will-change: transform; }
@media (prefers-reduced-motion: reduce) {
.motion-reduce\\:animate-none { animation: none; }
}
"""
def launch_browser(pw):
try:
return pw.chromium.launch(headless=True)
except Exception:
return pw.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
with sync_playwright() as pw:
browser = launch_browser(pw)
page = browser.new_page(viewport={"width": 800, "height": 600})
page.set_content(f"""<!doctype html><html><head><style>{CSS}</style></head><body>
<button id="b-hover" class="bg-green-500 hover:bg-green-600 hover:shadow-md" style="width:120px;height:40px;">Hover</button>
<input id="inp-focus" class="border focus:border-blue-500 focus:ring-2 outline-none" />
<button id="b-active" class="bg-red-500 active:bg-red-700 active:scale-95" style="width:120px;height:40px;">Active</button>
<button id="b-dis" class="cursor-not-allowed" disabled>Disabled</button>
<div id="t-box" class="w-20 h-20 hover:w-40 transition-all duration-300 ease-in-out"></div>
<button id="t-scale" class="bg-blue-500 hover:scale-105" style="width:100px;height:40px;">Scale</button>
<div id="t-card" class="hover:-translate-y-1" style="width:160px;height:80px;">Card</div>
<div id="a-spin" class="animate-spin">Spin</div>
<div id="a-ping" class="animate-ping">Ping</div>
<div id="a-pulse" class="animate-pulse">Pulse</div>
<div id="a-bounce" class="animate-bounce">Bounce</div>
<div id="a-slow" class="animate-spin-slow">Slow</div>
<div id="a-wiggle" class="animate-wiggle">Wiggle</div>
<div id="wc-box" class="will-change-transform">WC</div>
<div id="rm-box" class="animate-bounce motion-reduce:animate-none">RM</div>
</body></html>""")
# Case 1: interactive states (hover, focus, active, disabled)
hover_before = page.eval_on_selector("#b-hover", "el => getComputedStyle(el).backgroundColor")
page.hover("#b-hover")
hover_after = page.eval_on_selector("#b-hover", "el => ({bg: getComputedStyle(el).backgroundColor, shadow: getComputedStyle(el).boxShadow !== 'none'})")
page.focus("#inp-focus")
focus_state = page.eval_on_selector("#inp-focus", "el => ({border: getComputedStyle(el).borderTopColor, ring: getComputedStyle(el).boxShadow, outline: getComputedStyle(el).outlineStyle})")
box = page.locator("#b-active").bounding_box()
page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
page.mouse.down()
page.wait_for_function(
"() => getComputedStyle(document.querySelector('#b-active')).backgroundColor === 'rgb(185, 28, 28)'"
)
active_state = page.eval_on_selector("#b-active", "el => ({bg: getComputedStyle(el).backgroundColor, tf: getComputedStyle(el).transform})")
page.mouse.up()
dis_state = page.eval_on_selector("#b-dis", "el => ({disabled: el.disabled, cursor: getComputedStyle(el).cursor})")
c1_act = {
"hover_before": hover_before,
"hover_after_bg": hover_after["bg"],
"hover_has_shadow": hover_after["shadow"],
"focus_border": focus_state["border"],
"focus_ring": focus_state["ring"],
"active_bg": active_state["bg"],
"active_scale": active_state["tf"],
"disabled_attr": dis_state["disabled"],
"disabled_cursor": dis_state["cursor"],
}
c1_exp = {
"hover_before": "rgb(34, 197, 94)",
"hover_after_bg": "rgb(22, 163, 74)",
"hover_has_shadow": True,
"focus_border": "rgb(59, 130, 246)",
"focus_ring": "rgb(191, 219, 254) 0px 0px 0px 2px",
"active_bg": "rgb(185, 28, 28)",
"active_scale": "matrix(0.95, 0, 0, 0.95, 0, 0)",
"disabled_attr": True,
"disabled_cursor": "not-allowed",
}
cases.append(dict(name="interactive_state_variants", expected=c1_exp, actual=c1_act, passed=(c1_act == c1_exp)))
# Case 2: transitions & transforms
t_meta = page.eval_on_selector("#t-box", "el => ({w: getComputedStyle(el).width, prop: getComputedStyle(el).transitionProperty, dur: getComputedStyle(el).transitionDuration})")
page.hover("#t-scale")
scale_tf = page.eval_on_selector("#t-scale", "el => getComputedStyle(el).transform")
page.hover("#t-card")
card_tf = page.eval_on_selector("#t-card", "el => getComputedStyle(el).transform")
c2_act = {
"initial_width": t_meta["w"],
"transition_prop": t_meta["prop"],
"transition_dur": t_meta["dur"],
"hover_scale_105": scale_tf,
"hover_translate_y_neg4": card_tf,
}
c2_exp = {
"initial_width": "80px",
"transition_prop": "all",
"transition_dur": "0.3s",
"hover_scale_105": "matrix(1.05, 0, 0, 1.05, 0, 0)",
"hover_translate_y_neg4": "matrix(1, 0, 0, 1, 0, -4)",
}
cases.append(dict(name="transitions_and_transforms", expected=c2_exp, actual=c2_act, passed=(c2_act == c2_exp)))
# Case 3: preset & custom keyframe animations
c3_act = page.evaluate("""() => {
const anim = id => {
const s = getComputedStyle(document.getElementById(id));
return [s.animationName, s.animationDuration, s.animationIterationCount];
};
return {
spin: anim('a-spin'),
ping: anim('a-ping'),
pulse: anim('a-pulse'),
bounce: anim('a-bounce'),
spin_slow: anim('a-slow'),
wiggle: anim('a-wiggle'),
};
}""")
c3_exp = {
"spin": ["spin", "1s", "infinite"],
"ping": ["ping", "1s", "infinite"],
"pulse": ["pulse", "2s", "infinite"],
"bounce": ["bounce", "1s", "infinite"],
"spin_slow": ["spin", "3s", "infinite"],
"wiggle": ["wiggle", "1s", "infinite"],
}
cases.append(dict(name="preset_and_custom_keyframes", expected=c3_exp, actual=c3_act, passed=(c3_act == c3_exp)))
# Case 4: will-change & prefers-reduced-motion
wc_val = page.eval_on_selector("#wc-box", "el => getComputedStyle(el).willChange")
rm_default = page.eval_on_selector("#rm-box", "el => getComputedStyle(el).animationName")
page.emulate_media(reduced_motion="reduce")
rm_reduced = page.eval_on_selector("#rm-box", "el => getComputedStyle(el).animationName")
c4_act = {
"will_change": wc_val,
"default_motion_anim": rm_default,
"reduced_motion_anim": rm_reduced,
}
c4_exp = {
"will_change": "transform",
"default_motion_anim": "bounce",
"reduced_motion_anim": "none",
}
cases.append(dict(name="reduced_motion_and_will_change", expected=c4_exp, actual=c4_act, passed=(c4_act == c4_exp)))
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
transform 与 opacity 可由浏览器合成层处理,避免触发布局重排与大面积重绘;使用 outline-none 移除默认轮廓后必须用 focus:ring-* 或 focus:border-* 提供可见焦点替代样式,且应对连续动画搭配 motion-reduce:animate-none 适配减弱动态效果设置。