我用 SASS 做了一个动态的解决方案。可以配置:
它会自动计算关键帧百分比和项目之间的延迟。
// Demo styles
.fadecycle div {
opacity: 0;
position: absolute;
width: 200px;
line-height: 200px;
text-align: center;
}
.fadecycle div:nth-child(1) { background: lightsalmon; }
.fadecycle div:nth-child(2) { background: lightsteelblue; }
.fadecycle div:nth-child(3) { background: lightseagreen; }
.fadecycle div:nth-child(4) { background: lightskyblue; }
// Animation settings
$totalTime: 8s;
$items: 4;
$transitionSpeed: 1.5;
// Calculate transition + display time in seconds
$transitionTime: 0s + $totalTime / ($items * $transitionSpeed * 2);
$displayTime: (0s + $totalTime - ($transitionTime * $items)) / $items;
// Set transition for each element
@for $i from 1 through $items {
.fadecycle div:nth-child(#{$i}) {
// Delay is increased for each item
// starting with an offset of -$transitionTime so the first element is displayed on load
$delay: -$transitionTime + ($transitionTime + $displayTime) * ($i - 1);
animation: fadeinout $totalTime linear $delay infinite;
}
}
// Calculate percentages of the times for keyframes
$transitionPercentage: 0% + 100 * ($transitionTime / $totalTime);
$displayPercentage: 0% + 100 * ($displayTime / $totalTime);
@keyframes fadeinout {
0% {
opacity: 0;
}
#{$transitionPercentage},
#{$transitionPercentage + $displayPercentage} {
opacity: 1;
}
#{$transitionPercentage + $displayPercentage + $transitionPercentage},
100% {
opacity: 0;
}
}