基本配置
CSS3 动画主要包括两个部分:
- 关键帧动画:定义动画的变化过程。
- 元素样式:应用动画到具体的元素上。
示例代码
假设我们要创建一个简单的动画,使一个元素从左向右平移,并在过程中改变颜色。
HTML 部分
<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS3 Animation Example</title>
<style>
/* 定义关键帧动画 */
@keyframes moveAndChangeColor {
0% { transform: translateX(0); background-color: red; }
50% { transform: translateX(50%); background-color: yellow; }
100% { transform: translateX(100%); background-color: green; } }
/* 应用动画到元素 */
.animated-box {
width: 100px; height: 100px;
background-color: red;
animation: moveAndChangeColor 3s linear infinite;
}
</style>
</head>
<body>
<div class="animated-box"></div>
</body>
</html>
解释
-
定义关键帧动画:
- 使用
@keyframes
规则定义一个名为moveAndChangeColor
的动画。 - 在
0%
时,元素位于初始位置,背景颜色为红色。 - 在
50%
时,元素平移到屏幕宽度的 50%,背景颜色变为黄色。 - 在
100%
时,元素平移到屏幕宽度的 100%,背景颜色变为绿色。
- 使用
-
应用动画到元素:
- 选择器
.animated-box
应用于一个div
元素。 - 设置动画属性
animation
,包括动画名称、持续时间、动画曲线(线性)、是否无限循环。
- 选择器
更多属性
CSS3 动画还可以包含其他属性,例如:
animation-name
: 动画名称。animation-duration
: 动画持续时间。animation-timing-function
: 动画的速度曲线(例如linear
,ease
,ease-in
,ease-out
,ease-in-out
)。animation-delay
: 动画延迟时间。animation-iteration-count
: 动画播放次数(例如infinite
表示无限循环)。animation-direction
: 动画的方向(例如normal
,reverse
,alternate
,alternate-reverse
)。animation-fill-mode
: 动画填充模式(例如none
,forwards
,backwards
,both
)。animation-play-state
: 动画播放状态(例如running
,paused
)。
示例扩展
下面是一个更复杂的示例,展示多个动画属性的组合使用:
HTML 部分
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS3 Animation Example</title> <style> /* 定义关键帧动画 */ @keyframes moveAndChangeColor { 0% { transform: translateX(0); background-color: red; } 50% { transform: translateX(50%); background-color: yellow; } 100% { transform: translateX(100%); background-color: green; } } /* 应用动画到元素 */ .animated-box { width: 100px; height: 100px; background-color: red; position: relative; animation: moveAndChangeColor 3s ease-in-out 1s infinite alternate; } </style> </head> <body> <div class="animated-box"></div> </body> </html>
解释
animation-name: moveAndChangeColor
: 动画名称为moveAndChangeColor
。animation-duration: 3s
: 动画持续时间为 3 秒。animation-timing-function: ease-in-out
: 动画速度曲线为ease-in-out
。animation-delay: 1s
: 动画延迟 1 秒后开始。animation-iteration-count: infinite
: 动画无限循环。animation-direction: alternate
: 动画方向为交替。
这些示例展示了如何使用 CSS3 动画来创建丰富的视觉效果。你可以根据需要调整动画参数,以达到不同的效果。