试一试
animation-duration: 750ms;
animation-duration: 3s;
animation-duration: 0s;
<section class="flex-column" id="default-example">
<div class="animating" id="example-element"></div>
<button id="play-pause">Play</button>
</section>
#example-element {
animation-direction: alternate;
animation-iteration-count: infinite;
animation-name: slide;
animation-play-state: paused;
animation-timing-function: ease-in;
background-color: #1766aa;
border-radius: 50%;
border: 5px solid #333333;
color: white;
height: 150px;
margin: auto;
margin-left: 0;
width: 150px;
}
#example-element.running {
animation-play-state: running;
}
#play-pause {
font-size: 2rem;
}
@keyframes slide {
from {
background-color: orange;
color: black;
margin-left: 0;
}
to {
background-color: orange;
color: black;
margin-left: 80%;
}
}
const el = document.getElementById("example-element");
const button = document.getElementById("play-pause");
button.addEventListener("click", () => {
if (el.classList.contains("running")) {
el.classList.remove("running");
button.textContent = "Play";
} else {
el.classList.add("running");
button.textContent = "Pause";
}
});
通常,为了图方便,可以使用简写属性 animation 一次性设置所有动画属性。
语法
css
/* Single animation */
animation-duration: auto; /* Default */
animation-duration: 6s;
animation-duration: 120ms;
/* Multiple animations */
animation-duration: 1.64s, 15.22s;
animation-duration: 10s, 35s, 230ms;
/* Global values */
animation-duration: inherit;
animation-duration: initial;
animation-duration: revert;
animation-duration: revert-layer;
animation-duration: unset;
值
auto-
对于基于时间的动画,
auto等同于0s(见下文)。对于CSS 滚动驱动动画,auto会用动画填充整个时间线。 <time>-
动画完成一个周期所需的时间。这可以以秒(
s)或毫秒(ms)为单位指定。值必须为正数或零,并且单位是必需的。如果未提供值,则使用默认值
0s,在这种情况下动画仍然会执行(会触发animationStart和animationEnd事件)。当持续时间为0s时,动画是否可见将取决于animation-fill-mode的值,如下所述。- 如果
animation-fill-mode设置为backwards或both,则在animation-delay倒计时期间将显示由animation-direction定义的动画的第一帧。 - 如果
animation-fill-mode设置为forwards或both,则在animation-delay过期后,将显示由animation-direction定义的动画的最后一帧。 - 如果
animation-fill-mode设置为none,则动画将没有可见效果。
- 如果
注意:负值无效,会导致声明被忽略。一些早期的、带前缀的实现可能会将它们视为与 0s 相同。
备注: 当你在一个 animation-* 属性上指定多个逗号分隔的值时,它们会按照 animation-name 出现的顺序应用于动画。对于动画数量和 animation-* 属性值不匹配的情况,请参见设置多个动画属性值。
注意:在创建 CSS 滚动驱动动画时,以秒或毫秒为单位指定 animation-duration 值并没有真正意义。在测试中,它似乎对滚动进度时间线动画没有影响,而在视图进度时间线动画中,它似乎将动画推到时间线的末尾附近发生。然而,Firefox 要求设置 animation-duration 才能成功应用动画。因此建议将 animation-duration 设置为 1ms,以便动画在 Firefox 中正常工作,但其效果不会被改变太多。
正式定义
正式语法
animation-duration =
[ auto | <time [0s,∞]> ]#
示例
设置动画持续时间
此动画的 animation-duration 为 0.7 秒。
HTML
html
<div class="box"></div>
CSS
css
.box {
background-color: rebeccapurple;
border-radius: 10px;
width: 100px;
height: 100px;
}
.box:hover {
animation-name: rotate;
animation-duration: 0.7s;
}
@keyframes rotate {
0% {
transform: rotate(0);
}
100% {
transform: rotate(360deg);
}
}
结果
将鼠标悬停在矩形上以启动动画。
有关更多示例,请参阅 CSS 动画。
规范
| 规范 |
|---|
| CSS 动画级别 1 # animation-duration |
浏览器兼容性
加载中…