为什么此CSS @keyframes规则不交叉渐变?

时间:2019-02-28 16:01:26

标签: html css animation cross-fade

我正在尝试创建一个非常简单的幻灯片显示,该幻灯片显示每个图像之间都可以渐变。问题在于图像在之前逐渐淡出。

我希望每张图像淡入淡出1秒钟,再保持10秒钟,然后淡出淡出1秒钟-总计12秒钟。

@关键帧是通过将动画持续时间除以100得出的,每秒得出1.81%。

动画延迟为11秒,这使我感到困惑,因为随着最后一张图像的淡出,下一张图像应该逐渐淡入。

如果有人可以阐明我做错了什么,那我将非常感激。

HTML:

<!doctype html>
<html>
    <body>
        <main>
            <div id="cf">
                <img src="https://placeimg.com/640/480/animals">
                <img src="https://placeimg.com/640/480/nature">
                <img src="https://placeimg.com/640/480/tech">
                <img src="https://placeimg.com/640/480/people">
                <img src="https://placeimg.com/640/480/sepia">
            </div>
        </main>
    </body>
</html>

CSS:

@keyframes crossFade{
    0%{opacity: 0;}
    1.81%{opacity: 1;}
    18.18%{opacity: 1;}
    19.98%{opacity: 0;}
    100%{opacity: 0;}
}

#cf img{
    position:absolute;
    left:0;
    opacity: 0;
    animation-name: crossFade;
    animation-duration: 55s;
    animation-iteration-count: infinite;
}

#cf img:nth-last-of-type(1){
    animation-delay: 0s;
}

#cf img:nth-last-of-type(2){
    animation-delay: 11s;
}

#cf img:nth-last-of-type(3){
    animation-delay: 22s;
}

#cf img:nth-last-of-type(4){
    animation-delay: 33s;
}

#cf img:nth-last-of-type(5){
    animation-delay: 44s;
}

链接到Codepen: https://codepen.io/Musicky/pen/YgyOPm

1 个答案:

答案 0 :(得分:0)

我更改了您的百分比和持续时间。这样会显示出您所期望的样子。

您可能要调整第一次过渡开始时的长度,但是原始原稿没有重叠。当事物是可分割的时,它更容易计时。不是说无法做到,而是难以实现

@keyframes crossFade{
    0%{opacity: 0;}
    10%{opacity: 1;}
    20%{opacity: 1;}
    30%{opacity: 0;}
    100%{opacity: 0;}
}
#cf img{
    position:absolute;
    left:0;
    opacity: 0;
    animation-name: crossFade;
    animation-duration: 60s;
    animation-iteration-count: infinite;
}
#cf img:nth-last-of-type(1){
    animation-delay: 0s;
}
#cf img:nth-last-of-type(2){
    animation-delay: 10s;
}
#cf img:nth-last-of-type(3){
    animation-delay: 20s;
}
#cf img:nth-last-of-type(4){
    animation-delay: 30s;
}
#cf img:nth-last-of-type(5){
    animation-delay: 40s;
}
<div id="cf">
    <img src="https://placeimg.com/640/480/animals">
    <img src="https://placeimg.com/640/480/nature">
    <img src="https://placeimg.com/640/480/tech">
    <img src="https://placeimg.com/640/480/people">
    <img src="https://placeimg.com/640/480/sepia">
</div>