CSS3动画实现方式全解析

CSS3 提供了强大的动画功能,主要通过 @keyframes
规则和 animation
属性来实现。以下是 CSS3 动画的主要实现方式:
1. @keyframes
规则
@keyframes
用于定义动画的关键帧。你可以指定动画在不同时间点的样式。
@keyframes example {
0% { background-color: red; }
50% { background-color: yellow; }
100% { background-color: green; }
}
2. animation
属性
animation
属性是一个简写属性,用于将动画应用到元素上。它包括以下子属性:
animation-name
: 指定@keyframes
的名称。animation-duration
: 指定动画的持续时间。animation-timing-function
: 指定动画的速度曲线(如ease
,linear
,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
)。
div {
width: 100px;
height: 100px;
background-color: red;
animation-name: example;
animation-duration: 4s;
animation-timing-function: ease-in-out;
animation-delay: 1s;
animation-iteration-count: infinite;
animation-direction: alternate;
}
3. 简写形式
你可以使用 animation
属性的简写形式来简化代码:
div {
animation: example 4s ease-in-out 1s infinite alternate;
}
4. 示例
以下是一个完整的示例,展示如何使用 CSS3 动画:
<!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 slidein {
from {
margin-left: 100%;
width: 300%;
}
to {
margin-left: 0%;
width: 100%;
}
}
div {
width: 100px;
height: 100px;
background-color: red;
animation: slidein 3s ease-in-out infinite alternate;
}
</style>
</head>
<body>
<div></div>
</body>
</html>
5. 其他动画属性
除了 @keyframes
和 animation
,CSS3 还提供了其他一些与动画相关的属性,如 transition
,用于在元素状态变化时应用平滑的过渡效果。
div {
width: 100px;
height: 100px;
background-color: red;
transition: width 2s, height 2s, background-color 2s;
}
div:hover {
width: 200px;
height: 200px;
background-color: blue;
}
总结
CSS3 动画通过 @keyframes
和 animation
属性提供了强大的动画功能,可以创建复杂的动画效果。结合 transition
属性,可以实现更加丰富的交互效果。