我在2016年1月学习了CSS3的@keyframes
语法,并且两年多后,我现在发现自己在很多工作中都使用了@keyframes
动画(比CSS3转换更复杂,比基于JavaScript的动画更简便)。
但我确实想要的是用秒来表示@keyframes
而不是百分比的能力。有没有什么技巧可以实现这一点呢?
我知道我可以使用以下100s
技巧循环播放彩虹色,每3秒一个周期:
div {
width: 120px;
height: 120px;
background-color: violet;
animation: myAnimation 100s;
}
@keyframes myAnimation {
0% {background-color: red;}
3% {background-color: orange;}
6% {background-color: yellow;}
9% {background-color: green;}
12% {background-color: cyan;}
15% {background-color: blue;}
18% {background-color: violet;}
100% {background-color: violet;}
}
<div></div>
但这意味着动画在完成后仍然运行了另外82秒(虽然几乎不可察觉)。除了其他问题之外,这也导致多次迭代无法达成。
实际上,我想写的是:
@keyframes myAnimation {
0s {background-color: red;}
3s {background-color: orange;}
6s {background-color: yellow;}
9s {background-color: green;}
12s {background-color: cyan;}
15s {background-color: blue;}
18s {background-color: violet;}
}
有没有比我在上面代码框中详细介绍的方法更好的方法?
使用多个元素的示例
事后我意识到,上面的示例可能太简单了,因为它只涉及一个元素的动画,而我的问题最初源于想要将多个元素同步动画。
因此,这里是一个稍微复杂一些的示例,展示了一个更接近引起我问题的设置:
div {
display: inline-block;
width: 48px;
height: 48px;
margin-right: 6px;
}
div:nth-of-type(1) {
background-color: red;
}
div:nth-of-type(2) {
background-color: orange;
animation: myAnimationOrange 100s;
}
div:nth-of-type(3) {
background-color: yellow;
animation: myAnimationYellow 100s;
}
div:nth-of-type(4) {
background-color: green;
animation: myAnimationGreen 100s;
}
div:nth-of-type(5) {
background-color: cyan;
animation: myAnimationCyan 100s;
}
div:nth-of-type(6) {
background-color: violet;
animation: myAnimationViolet 100s;
}
@keyframes myAnimationOrange {
0% {background-color: white;}
1% {background-color: white;}
2% {background-color: orange;}
100% {background-color: orange;}
}
@keyframes myAnimationYellow {
0% {background-color: white;}
2% {background-color: white;}
3% {background-color: yellow;}
100% {background-color: yellow;}
}
@keyframes myAnimationGreen {
0% {background-color: white;}
3% {background-color: white;}
4% {background-color: green;}
100% {background-color: green;}
}
@keyframes myAnimationCyan {
0% {background-color: white;}
4% {background-color: white;}
5% {background-color: cyan;}
100% {background-color: cyan;}
}
@keyframes myAnimationViolet {
0% {background-color: white;}
5% {background-color: white;}
6% {background-color: violet;}
100% {background-color: violet;}
}
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
px
、vw
(它们的工作方式不同)或%
(又有不同的工作方式)来表示“宽度”。这些中的任何一个都不会限制其他的。 - Rounin20s
的过程,并且我使用5%
,10%
来标记每个关键帧。现在,假设我想要添加另外 3 个项目。所以我将持续时间更新为23s
,然后...我必须浏览所有的百分比并将5%
更改为4.345%
,10%
更改为8.69%
,15%
更改为13.035%
等。 - Rounin