原生复选框:checked无法直接过渡动画,需隐藏input并用:checked + label控制自定义视觉元素的可动画属性(如transform、background-color);SVG打钩动画须通过stroke-dashoffset过渡,且须保障移动端点击热区≥44×44px及aria-checked同步更新。

复选框原生:checked状态无法直接过渡动画
浏览器对input[type="checkbox"]的勾选状态切换是离散的(true/false),不支持对:checked伪类本身做transition。你写input:checked { transition: all 0.3s; }完全无效——这不是写错了,是 CSS 规范根本不允许。
真正能过渡的,必须是可动画的 CSS 属性,比如opacity、transform、scale、background-color(需支持颜色空间插值),且这些属性得作用在「可见的自定义控件」上,而不是原生复选框本身。
用:checked + label触发视觉层动画
标准解法是隐藏原生input,用紧邻的label(或其子元素)模拟勾选外观,并通过:checked + .custom-check这类组合选择器控制动画。关键点在于:动画必须加在被选中的视觉元素上,而非input。
- 确保
input和label在 DOM 中相邻,且label有for属性或包裹input,否则:checked + .xxx不生效 -
label内用于显示勾号的元素(如::after)必须设content: ""且为块级/行内块,否则transform无效 - 过渡要写在「未勾选时的默认样式」里,而不是只写在
:checked里;否则第一次勾选没动画
input[type="checkbox"] {
display: none;
}
.custom-checkbox .checkmark {
display: inline-block;
width: 18px;
height: 18px;
border: 2px solid #999;
position: relative;
transition: all 0.25s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}
input:checked + .custom-checkbox .checkmark::after {
content: "";
position: absolute;
left: 4px;
top: 1px;
width: 6px;
height: 10px;
border: solid white;
border-width: 0 2px 2px 0;
transform: rotate(45deg) scale(0);
transition: transform 0.2s 0.05s;
}
input:checked + .custom-checkbox .checkmark {
background-color: #007bff;
border-color: #007bff;
}
input:checked + .custom-checkbox .checkmark::after {
transform: rotate(45deg) scale(1);
}
SVG 图标比::after更可控,但要注意stroke-dasharray路径动画
如果要用 SVG 打钩动画(比如画线式出现),核心是控制stroke-dasharray和stroke-dashoffset。但别直接给svg path加transition——它只对数值型属性有效,而stroke-dasharray是列表,多数浏览器不支持列表过渡。
立即学习“前端免费学习笔记(深入)”;
- 正确做法:把
stroke-dasharray固定为路径总长,用stroke-dashoffset从全长过渡到 0 - 必须提前用 JS 或工具算出路径精确长度(
getTotalLength()),硬编码进 CSS 容易错位 - SVG 需设
fill: none、stroke: currentColor,否则颜色无法继承父级主题 - 动画延迟建议加在
stroke-dashoffset上,避免勾号突然弹出
移动端点击区域和可访问性容易被忽略
为了平滑动画把label做小了?或者用pointer-events: none误关了交互?这会导致 iOS Safari 点击失灵或屏幕阅读器无法识别控件。
-
label的点击热区至少保持 44×44px(苹果人机指南),可用padding撑开,别只靠width/height - 隐藏原生
input时,别用visibility: hidden或opacity: 0——它们仍占布局且部分读屏器会跳过;用position: absolute; clip-path: inset(50%)更稳妥 - 务必保留
aria-checked同步更新(JS 控制),否则 VoiceOver 不知道当前状态
打钩动画本身不是难点,难的是在动效、可访问性、跨端兼容之间找到那个刚好不破防的平衡点——多点一次真机测试,比调十次 Chrome 动画曲线管用。










