cubic-bezier 缓动函数的原理是什么?如何自定义?
cubic-bezier() 定义动画的速度曲线,通过两个控制点决定贝塞尔曲线的形状。
语法
transition-timing-function: cubic-bezier(x1, y1, x2, y2);(x1, y1):第一个控制点(x2, y2):第二个控制点- 起点固定为 (0, 0),终点固定为 (1, 1)
- x 轴表示时间进度(0
1),y 轴表示动画进度(01) - x1 和 x2 必须在 0~1 范围内,y 可以超出(产生回弹效果)
内置缓动函数对应
ease = cubic-bezier(0.25, 0.1, 0.25, 1)
linear = cubic-bezier(0, 0, 1, 1)
ease-in = cubic-bezier(0.42, 0, 1, 1)
ease-out = cubic-bezier(0, 0, 0.58, 1)
ease-in-out = cubic-bezier(0.42, 0, 0.58, 1)常用自定义曲线
/* 弹性效果(轻微回弹) */
.bounce {
transition: transform 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}
/* 苹果风格弹性 */
.apple-ease {
transition: transform 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
}
/* 快速开始,缓慢结束 */
.quick-start {
transition: all 0.3s cubic-bezier(0.1, 0.9, 0.3, 1);
}
/* Material Design 标准缓动 */
.material-standard {
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
/* Material 加速缓动 */
.material-accelerate {
transition: all 0.3s cubic-bezier(0.4, 0, 1, 1);
}
/* Material 减速缓动 */
.material-decelerate {
transition: all 0.3s cubic-bezier(0, 0, 0.2, 1);
}y 值超出 [0,1] 的效果
当 y1 或 y2 小于 0 或大于 1 时,动画进度会超出目标值,产生回弹/弹性效果:
/* y1 = -0.55,动画先超过目标再回弹 */
transform: translateY(-10px);
transition: transform 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55);调试工具
- Chrome DevTools → Animations 面板可以可视化调整贝塞尔曲线
- 在线工具:cubic-bezier.com
选择建议
- UI 交互反馈:ease-out(快速响应,缓慢结束)
- 入场动画:cubic-bezier(0.34, 1.56, 0.64, 1)(弹性入场)
- 退场动画:ease-in(缓慢开始,快速消失)
- Material Design:
cubic-bezier(0.4, 0, 0.2, 1)