css3 动画制作
关键属性与基础语法
CSS3动画通过@keyframes规则和动画属性实现。定义关键帧需指定动画名称和阶段样式,例如:
@keyframes slideIn {
0% { transform: translateX(-100%); }
100% { transform: translateX(0); }
}
应用动画时使用简写属性:
.element {
animation: slideIn 1s ease-in-out forwards;
}
核心动画属性详解
animation-name
绑定@keyframes定义的动画名称,如slideIn。
animation-duration
设置动画周期时长,单位可为秒(1s)或毫秒(500ms)。
animation-timing-function
控制速度曲线:

ease(默认):慢快慢linear:匀速cubic-bezier():自定义贝塞尔曲线
animation-delay
定义动画开始前的延迟时间,负值使动画从中间开始。
animation-iteration-count
指定重复次数:infinite表示无限循环。
animation-direction
控制播放方向:

normal(默认)reverse(反向播放)alternate(往返交替)
animation-fill-mode
决定动画结束后的状态:
forwards:保留最后一帧样式backwards:应用第一帧样式both:结合两者特性
复合动画示例
组合多个动画效果:
@keyframes fadeAndRotate {
0% { opacity: 0; transform: rotate(0deg); }
100% { opacity: 1; transform: rotate(360deg); }
}
.box {
animation: fadeAndRotate 2s ease-in 0.5s infinite alternate;
}
性能优化建议
优先使用transform和opacity属性,这些属性不会触发重排(reflow),可通过GPU加速。避免频繁修改width、height或margin等属性。
浏览器兼容处理
添加前缀确保兼容旧版浏览器:
@-webkit-keyframes example { /*...*/ }
.element {
-webkit-animation: example 2s;
animation: example 2s;
}
调试技巧
使用浏览器开发者工具的Animations面板(Chrome)可视化调试时间轴,调整缓动函数和持续时间。






