transition-delay 及 animation-delay 的负值使用,立刻开始动画【css】

时间:2019-10-01 发布者: 访问量:3979



我们知道,CSS 动画及过渡提供了一个 delay 属性,可以延迟动画的进行。

考虑下面这个动画:

简单的代码大概是这样:

<div class="g-container"> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> 复制代码
.item { transform: rotate(0) translate(-80px, 0) ;
} .item:nth-child(1) { animation: rotate 3s infinite linear;
} .item:nth-child(2) { animation: rotate 3s infinite 1s linear;
} .item:nth-child(3) { animation: rotate 3s infinite 2s linear;
}


@keyframes rotate {
    100% { transform: rotate(360deg) translate(-80px, 0) ;
    }
} 复制代码

如果,我们想去掉这个延迟,希望在一进入页面的时候,3 个球就是同时运动的。这个时候,只需要把正向的 animation-delay 改成负向的即可。

.item:nth-child(1) { animation: rotate 3s infinite linear;
} .item:nth-child(2) { animation: rotate 3s infinite -1s linear;
} .item:nth-child(3) { animation: rotate 3s infinite -2s linear;
} 复制代码

这里,有个小技巧,被设置了animation-dealy为负值的动画会立刻执行,开始的位置是其动画阶段中的一个阶段。所以,动画在一开始的时刻就是下面这样:

以上述动画为例,一个被定义执行 3s 的动画,如果animation-delay为 -1s,起点相当于正常执行时,第2s(3-1)时的位置。


发布于
  用户评论
    生活编程