CSS动画与过渡
CSS动画与过渡为页面添加动态效果,提升用户体验和交互反馈。
CSS过渡
基本语法
CSS
.box {
transition: property duration timing-function delay;
}
.box:hover {
transform: scale(1.1);
}
过渡属性详解
CSS
.box {
transition-property: all; /* 过渡的属性 */
transition-duration: 0.3s; /* 过渡时长 */
transition-timing-function: ease; /* 缓动函数 */
transition-delay: 0s; /* 延迟时间 */
}
/* 简写 */
.box {
transition: transform 0.3s ease 0s;
}
缓动函数
| 值 | 说明 |
|---|---|
| ease | 慢开始,中间快,慢结束(默认) |
| linear | 匀速 |
| ease-in | 慢开始 |
| ease-out | 慢结束 |
| ease-in-out | 慢开始和结束 |
| cubic-bezier(n,n,n,n) | 自定义贝塞尔曲线 |
CSS动画
定义关键帧
CSS
@keyframes slideIn {
from {
transform: translateX(-100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
/* 或使用百分比 */
@keyframes bounce {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-20px); }
}
应用动画
CSS
.box {
animation-name: slideIn;
animation-duration: 0.5s;
animation-timing-function: ease-out;
animation-delay: 0s;
animation-iteration-count: 1;
animation-direction: normal;
animation-fill-mode: forwards;
animation-play-state: running;
}
/* 简写 */
.box {
animation: slideIn 0.5s ease-out forwards;
}
动画属性说明
| 属性 | 说明 |
|---|---|
| animation-name | 关键帧名称 |
| animation-duration | 动画时长 |
| animation-timing-function | 缓动函数 |
| animation-delay | 延迟时间 |
| animation-iteration-count | 播放次数(infinite 无限) |
| animation-direction | 方向(normal/reverse/alternate) |
| animation-fill-mode | 结束状态(forwards/backwards/both) |
| animation-play-state | 播放状态(running/paused) |
过渡与动画对比
| 特性 | 过渡 | 动画 |
|---|---|---|
| 触发方式 | 状态变化(hover等) | 自动播放 |
| 关键帧 | 仅起止状态 | 可定义多个关键帧 |
| 循环播放 | 不支持 | 支持 |
| 复杂程度 | 简单 | 复杂 |
注意:动画优先使用
transform和opacity属性,可触发GPU加速,性能更优。
要点总结
- 过渡适合简单状态切换,动画适合复杂序列
animation-fill-mode: forwards保持动画结束状态- 使用
transform和opacity实现高性能动画 - 缓动函数影响动画节奏,
ease为默认值
存放路径:articles/CSS/入门/CSS样式属性/CSS动画与过渡.md
📝 发现内容有误?点击此处直接编辑