如何同步两个CSS动画时间



我想让一个CSS动画同步,以便进度条填充和背景变化在同一时间。

例如,在我的例子中,进度条应该花费5000ms,然后每5000ms背景图像应该改变。

我认为我已经正确地设置了背景动画持续时间为20000ms,每一步以25%的间隔变化,但这只是没有正确同步。

我在这里错过了什么,或者它是不是真的不可行的东西像这样准确地同步?

.progress-bar {
width: 100%;
height: 30px; 
background-color: black;
}
.progress-bar > div {
background-color: blue;
height: 30px;
animation: progress-bar 5000ms linear;
animation-iteration-count: infinite;
}
.container {
width: 100%;
height: 500px;
animation: bg 20000ms linear;
animation-iteration-count: infinite;
}
@keyframes progress-bar {
0% {
width: 0px;
}
100% {
width: 100%;
}
}
@keyframes bg {
0% {background-image: url("https://source.unsplash.com/1600x900/?nature,water");}
25% {background-image: url("https://source.unsplash.com/1600x900/?mountain");}
50% {background-image: url("https://source.unsplash.com/1600x900/?tree");}
75% {background-image: url("https://source.unsplash.com/1600x900/?river");}
}
<div class="container">
<div class="progress-bar"><div></div></div>
</div>

你做得差不多了,你需要通过添加更多步骤来避免过渡

.progress-bar {
width: 100%;
height: 30px; 
background-color: black;
}
.progress-bar > div {
background-color: blue;
height: 30px;
animation: progress-bar 5000ms linear;
animation-iteration-count: infinite;
}
.container {
width: 100%;
height: 500px;
animation: bg 20000ms linear;
animation-iteration-count: infinite;
}
@keyframes progress-bar {
0% {
width: 0px;
}
100% {
width: 100%;
}
}
@keyframes bg {
0%,24.9% {background-image: url("https://source.unsplash.com/1600x900/?nature,water");}
25%,49.9% {background-image: url("https://source.unsplash.com/1600x900/?mountain");}
50%,74.9% {background-image: url("https://source.unsplash.com/1600x900/?tree");}
75%,100% {background-image: url("https://source.unsplash.com/1600x900/?river");}
}
<div class="container">
<div class="progress-bar"><div></div></div>
</div>

最新更新