使用Animation实现自定义动画
在 CSS 中,@keyframes
和 animation
属性可以用来创建自定义动画。通过定义关键帧(@keyframes
)和设置动画属性(如持续时间、延迟、重复次数等),可以实现复杂的动画效果。
1. 基本语法
1.1 定义关键帧(@keyframes
)
@keyframes
用于定义动画的关键帧,指定动画从开始到结束的样式变化。
css
@keyframes 动画名称 {
0% {
/* 初始状态 */
}
50% {
/* 中间状态 */
}
100% {
/* 结束状态 */
}
}
1.2 应用动画(animation
)
通过 animation
属性将动画应用到元素上。
css
.element {
animation: 动画名称 持续时间 动画速度曲线 延迟 重复次数 方向 填充模式;
}
2. 动画属性详解
属性 | 描述 |
---|---|
animation-name |
指定动画名称(与@keyframes 定义的名称一致)。 |
animation-duration |
动画的持续时间(如2s 或 500ms )。 |
animation-timing-function |
动画的速度曲线(如ease 、linear 、ease-in-out )。 |
animation-delay |
动画开始前的延迟时间(如1s )。 |
animation-iteration-count |
动画的重复次数(如2 或 infinite )。 |
animation-direction |
动画的方向(如normal 、reverse 、alternate 、alternate-reverse )。 |
animation-fill-mode |
动画执行前后的样式状态(如none 、forwards 、backwards 、both )。 |
animation-play-state |
控制动画的播放状态(如running 或 paused )。 |
3. 实现自定义动画
示例 1:简单的淡入淡出动画
css
@keyframes fadeInOut {
0% {
opacity: 0;
}
50% {
opacity: 1;
}
100% {
opacity: 0;
}
}
.element {
animation: fadeInOut 3s ease-in-out infinite;
}
示例 2:元素从左到右移动
css
@keyframes moveRight {
0% {
transform: translateX(0);
}
100% {
transform: translateX(200px);
}
}
.element {
animation: moveRight 2s linear infinite alternate;
}
示例 3:旋转动画
css
@keyframes rotate {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.element {
animation: rotate 2s linear infinite;
}
示例 4:复杂动画(结合多个属性)
css
@keyframes complexAnimation {
0% {
transform: translateX(0) rotate(0deg);
background-color: red;
}
50% {
transform: translateX(200px) rotate(180deg);
background-color: blue;
}
100% {
transform: translateX(0) rotate(360deg);
background-color: red;
}
}
.element {
animation: complexAnimation 4s ease-in-out infinite;
}
4. 控制动画播放
暂停和播放动画
通过 animation-play-state
控制动画的播放状态。
css
.element {
animation: moveRight 2s linear infinite;
animation-play-state: paused; /* 默认暂停 */
}
.element:hover {
animation-play-state: running; /* 悬停时播放 */
}
动画结束后保持最终状态
通过 animation-fill-mode
设置动画结束后的样式状态。
css
.element {
animation: moveRight 2s linear forwards;
}
5. 多动画组合
可以为同一个元素应用多个动画。
css
@keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@keyframes scaleUp {
0% {
transform: scale(1);
}
100% {
transform: scale(1.5);
}
}
.element {
animation: fadeIn 2s ease-in-out, scaleUp 2s ease-in-out;
}
6. 实际应用示例
按钮点击效果
css
@keyframes clickEffect {
0% {
transform: scale(1);
}
50% {
transform: scale(0.9);
}
100% {
transform: scale(1);
}
}
.button:active {
animation: clickEffect 0.2s ease-in-out;
}
加载动画
css
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.loader {
width: 40px;
height: 40px;
border: 4px solid #f3f3f3;
border-top: 4px solid #3498db;
border-radius: 50%;
animation: spin 1s linear infinite;
}
总结
- 使用
@keyframes
定义动画的关键帧。 - 通过
animation
属性将动画应用到元素上。 - 可以控制动画的持续时间、速度曲线、延迟、重复次数等。
- 支持多动画组合和动态控制播放状态。
通过灵活运用 CSS 动画,可以为网页添加丰富的交互效果,提升用户体验。
更多vue相关插件及后台管理模板可访问vue admin reference,代码详情请访问github