2026-10-22 23:21:31
CSS3 的 animation 属性用于创建动画效果,通过定义关键帧(@keyframes)和设置动画属性,可以实现元素的动态变化。以下是详细说明和示例:
核心属性animation 是以下属性的简写形式,顺序如下:
animation: name duration timing-function delay iteration-count direction fill-mode play-state;animation-name
定义动画名称(对应 @keyframes 的名称)。
示例:animation-name: go;
animation-duration
动画单次播放的持续时间(如 2s)。
示例:animation-duration: 3s;
animation-timing-function
速度曲线(如 ease、linear、cubic-bezier())。
示例:animation-timing-function: ease-in-out;
animation-delay
动画开始前的延迟时间(如 1s)。
示例:animation-delay: 0.5s;
animation-iteration-count
播放次数(number 或 infinite)。
示例:animation-iteration-count: 3;
animation-direction
是否反向播放(normal、reverse、alternate)。
示例:animation-direction: alternate;
animation-fill-mode
动画外的样式状态(none、forwards、backwards)。
示例:animation-fill-mode: forwards;
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>效果说明通过灵活组合这些属性,可以实现复杂的动画效果(如循环、反向、延迟启动等)。