博客主页: [小ᶻ☡꙳ᵃⁱᵍᶜ꙳] 本文专栏: 前端
在 CSS3 时代到来之前,网页中的动画通常通过 JavaScript 动态地改变元素的样式属性来实现。这种实现方式虽有效,但性能往往欠佳,特别是在复杂动画中显得效率低下。CSS3 的引入使得动画的实现更加简单,同时显著提高了性能和流畅性。
CSS3 提供了一个强大且简洁的工具:animation
,它类似于 Flash 中的逐帧动画。逐帧动画的概念与电影胶片相似,通过一系列关键帧的快速连续播放,最终实现顺滑自然的动画效果。相较于 CSS 的 transition
属性只能定义起始和结束状态,CSS3 中的 keyframes
则能够定义动画的多个关键步骤,使动画更为灵活和精细。
在 CSS3 中,通过 @keyframes
规则来定义关键帧,可以为每个动画创建多个不同的状态节点。
color
、left
、width
等,用于定义节点的样式。@keyframes myAnimation {
from {
opacity: 0;
}
50% {
opacity: 0.5;
transform: translateX(100px);
}
to {
opacity: 1;
}
}
在上述代码中,我们创建了一个名为 myAnimation
的动画,其中有三个关键帧,分别是 from
(相当于 0%)、50%
和 to
(相当于 100%)。动画从完全透明开始,过渡到半透明并移动位置,最后变得完全不透明。
CSS3 提供了一组强大的动画控制属性,通过 animation
简写方式可以一次性设置多个属性。
animation: name duration timing-function delay iteration-count direction fill-mode play-state;
animation-name
用于指定动画的名称,可定义多个动画名称,使用逗号分隔。
animation-name: none | IDENT[, none | IDENT] *;
animation-name: myAnimation, fadeIn;
默认值为 none
,表示没有指定任何动画。
animation-duration
用于设置动画的持续时间,单位为秒 (s
) 或毫秒 (ms
),默认值为 0
。
animation-duration: time>[, time>] *;
animation-duration: 2s, 1s;
这表示 myAnimation
的持续时间是 2 秒,而 fadeIn
持续 1 秒。
animation-timing-function
用于定义动画的过渡方式,控制速度曲线。
animation-timing-function: ease | linear | ease-in | ease-out | ease-in-out | cubic-bezier(number>, number>, number>, number>) | step-start | step-end;
animation-timing-function: ease, linear, cubic-bezier(0.25, 0.1, 0.25, 1.0);
animation-delay
设置动画的延迟时间,单位为秒 (s
) 或毫秒 (ms
)。
animation-delay: time>[, time>] *;
animation-delay: 500ms;
这表示动画将在 500 毫秒后开始。
animation-direction
用于控制动画的播放方向。
animation-direction: normal|reverse|alternate|alternate-reverse;
animation-direction: alternate;
animation-iteration-count
用于指定动画循环的次数,默认值为 1
。
animation-iteration-count: 3;
animation-iteration-count: infinite;
animation-iteration-count: infinite;这意味着动画将无限次循环播放。
animation-play-state
用于控制动画的播放状态:
animation-play-state: paused|running;
animation-play-state: paused;
animation-fill-mode
用于控制动画不播放时,元素应该处于的状态:
animation-fill-mode: none|forwards|backwards|both;
animation-fill-mode: forwards;
值 | 描述 |
---|---|
none | 默认值。动画在动画执行之前和之后不会应用任何样式到目标元素。 |
forwards | 在动画结束后(由 animation-iteration-count 决定),动画将应用该属性值。 |
backwards | 动画将应用在 animation-delay 定义期间启动动画的第一次迭代的关键帧中定义的属性值。这些都是 from 关键帧中的值(当 animation-direction 为 “normal” 或 “alternate” 时)或 to 关键帧中的值(当 animation-direction 为 “reverse” 或 “alternate-reverse” 时)。 |
both | 动画遵循 forwards 和 backwards 的规则。也就是说,动画会在两个方向上扩展动画属性。 |
动画库链接:Animate.css 是一个方便的 CSS 动画库,提供多种现成的动画效果。
示例:
link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
div class="animate__animated animate__bounce">动画效果/div>
CSS3 动画提供了一种高效且灵活的方式来实现网页元素的动画效果,通过定义关键帧 (@keyframes) 和一系列动画属性(如持续时间、延迟、循环次数等),开发者可以轻松地控制动画的各个细节,使动画更加生动流畅。此外,使用如 Animate.css 这样的动画库,还能快速应用多种现成动画效果,提高开发效率。总的来说,CSS3 动画使网页设计更加丰富、直观,且性能优于传统 JavaScript 实现。