CSS 动画

CSS 动画基础

CSS 动画允许您改变任何 CSS 属性的值。通过改变属性值,然后指定这些变化需要多长时间才能完成,您可以创建动画效果。

使用 @keyframes 规则创建动画

@keyframes 规则是用于定义动画的关键帧。关键帧是动画开始和结束时的状态,以及动画过程中的任意点。

应用动画到元素

要应用一个动画到元素上,使用 animation-name 属性来引用 @keyframes 规则,并且可以设置动画的其他属性如 animation-duration, animation-timing-function, animation-delay, animation-iteration-count, animation-direction, 和 animation-fill-mode

控制动画的速度曲线

animation-timing-function 属性定义了动画的速度曲线,它控制动画在不同时间点的速度。默认值为 ease,表示开始慢,中间快,结束慢。其他常用的值包括 linear(匀速)、ease-in(加速)、ease-out(减速)和 ease-in-out(先加速后减速)。

设置动画延迟

animation-delay 属性定义了动画何时开始。该属性接受一个时间值,表示从动画应用到元素上开始,直到动画开始执行之间的延迟时间。

设置动画的播放次数

animation-iteration-count 属性定义了动画应该播放多少次。默认值为 1,表示动画只播放一次。如果希望动画无限循环播放,可以将其设为 infinite

控制动画的方向

animation-direction 属性定义了动画是否在下一周期逆向播放。默认值为 normal,表示动画按正常顺序播放。如果设置为 alternate,则在奇数周期按正常顺序播放,在偶数周期按反向顺序播放。

设置动画完成后的行为

animation-fill-mode 属性定义了动画在不播放时(例如在 animation-delay 的延迟期间)如何显示。默认情况下,动画不应用样式。可以设置为 forwards,使元素保持最后一帧的样式;backwards,使元素保持第一帧的样式;both,结合两者的效果。

综合使用

下面是一个综合使用上述所有属性的例子:

-- -------------------- ---- -------
--- -
  ------ ------
  ------- ------
  ----------------- ----
  --------- ---------
  --------------- --------
  ------------------- ---
  -------------------------- --------
  ---------------- ---
  -------------------------- ---------
  -------------------- ----------
  -------------------- ---------
-
展开代码

CSS 动画与 JavaScript

虽然 CSS 动画非常强大,但有时您可能需要使用 JavaScript 来动态控制动画。例如,当用户交互发生时启动或停止动画。这可以通过 JavaScript 添加或删除类名,或者直接操作 DOM 元素的样式属性来实现。

在这个例子中,点击一个 div 元素会切换它的 animate 类,从而触发或停止 CSS 动画。

结语

本章介绍了如何使用 CSS 创建和控制动画。通过组合不同的 CSS 属性,您可以创建出复杂且富有创意的动画效果。记住,动画不仅能够提升用户体验,还能增强网页的视觉吸引力。希望这些技巧能帮助您设计出令人惊叹的动画效果。

属性
background
background-color
background-position
background-size
border
border-bottom
border-bottom-color
border-bottom-left-radius
border-bottom-right-radius
border-bottom-width
border-color
border-left
border-left-color
border-left-width
border-right
border-right-color
border-right-width
border-spacing
border-top
border-top-color
border-top-left-radius
border-top-right-radius
border-top-width
bottom
box-shadow
clip
color
column-count
column-gap
column-rule
column-rule-color
column-rule-width
column-width
columns
filter
flex
flex-basis
flex-grow
flex-shrink
font
font-size
font-size-adjust
font-stretch
font-weight
height
left
letter-spacing
line-height
margin
margin-bottom
margin-left
margin-right
margin-top
max-height
max-width
min-height
min-width
opacity
order
outline
outline-color
outline-offset
outline-width
padding
padding-bottom
padding-left
padding-right
padding-top
perspective
perspective-origin
right
text-decoration-color
text-indent
text-shadow
top
transform
transform-origin
vertical-align
visibility
width
word-spacing
z-index
纠错
反馈

纠错反馈