CSS3 animation 属性的使用

CSS3 animation 属性的使用
最新回答
靉哥哥旳文

2026-10-22 23:21:31

CSS3 的 animation 属性用于创建动画效果,通过定义关键帧(@keyframes)和设置动画属性,可以实现元素的动态变化。以下是详细说明和示例:

核心属性

animation 是以下属性的简写形式,顺序如下:

animation: name duration timing-function delay iteration-count direction fill-mode play-state;
  1. animation-name

    定义动画名称(对应 @keyframes 的名称)。

    示例:animation-name: go;

  2. animation-duration

    动画单次播放的持续时间(如 2s)。

    示例:animation-duration: 3s;

  3. animation-timing-function

    速度曲线(如 ease、linear、cubic-bezier())。

    示例:animation-timing-function: ease-in-out;

  4. animation-delay

    动画开始前的延迟时间(如 1s)。

    示例:animation-delay: 0.5s;

  5. animation-iteration-count

    播放次数(number 或 infinite)。

    示例:animation-iteration-count: 3;

  6. animation-direction

    是否反向播放(normal、reverse、alternate)。

    示例:animation-direction: alternate;

  7. animation-fill-mode

    动画外的样式状态(none、forwards、backwards)。

    示例:animation-fill-mode: forwards;

  8. animation-play-state

    控制播放/暂停(running、paused)。

    示例:animation-play-state: paused;

示例:控制小车移动

以下代码通过 animation-play-state 实现按钮控制小车启停:

<template> <div class="content"> <div class="car" :style="[Style]"> <img src="car.svg" alt="小车"> </div> <button @click="control()">{{ instructions }}</button> </div></template><script>export default { data() { return { Style: { "animation-play-state": "paused" }, instructions: "开始" }; }, methods: { control() { if (this.Style["animation-play-state"] === "paused") { this.Style["animation-play-state"] = "running"; this.instructions = "暂停"; } else { this.Style["animation-play-state"] = "paused"; this.instructions = "开始"; } } }};</script><style>.content { width: 1000px; height: 1000px; background: gray;}.car { width: 50px; height: 50px; animation: go 10s ease 1s 1 normal none;}@keyframes go { 0% { margin-left: 0; } 100% { margin-left: 900px; }}button { display: block; width: 50px; height: 30px; margin: 200px auto;}</style>效果说明
  • 小车从左侧移动到右侧(通过 @keyframes go 定义)。
  • 点击按钮切换 animation-play-state 实现暂停/继续。
  • 初始状态为 paused,点击后变为 running。
关键点总结
  1. 简写属性顺序:严格遵循 name duration timing-function delay iteration-count direction fill-mode play-state。
  2. 动态控制:通过 JavaScript 修改 animation-play-state 实现交互。
  3. 关键帧定义:@keyframes 需与 animation-name 匹配,定义动画过程。

通过灵活组合这些属性,可以实现复杂的动画效果(如循环、反向、延迟启动等)。