首页 > 解决方案 > CSS 动画:将图像淡入彼此并为图像设置动画并移动其方向

问题描述

我正在克隆 AirBnB 网站以练习使用 React。我正在尝试复制网站的 jumbotron 及其功能。

AirBnB 的网站上,jumbotron 图像逐渐淡入另一个。图像在显示时也会慢慢向上浮动。我无法模仿这一点。

我正在尝试使用这样的 CSS 关键帧:

    @keyframes fader {
  0% {
    background: url('./components/layout/images/jumbo1.jpg');
    background-size: cover;
  }
  16.67% {
    background: url('./components/layout/images/jumbo2.jpg');
    background-size: cover;
  }
  33.34% {
    background: url('./components/layout/images/jumbo3.jpg');
    background-size: cover;
  }
  50.01% {
    background: url('./components/layout/images/jumbo4.jpg');
    background-size: cover;
  }
  66.68% {
    background: url('./components/layout/images/jumbo5.jpg');
    background-size: cover;
  }
  83.35% {
    background: url('./components/layout/images/jumbo1.jpg');
    background-size: cover;
  }
  100% {
    background: url('./components/layout/images/jumbo2.jpg');
    background-size: cover;
  }
}



.wrapper {
  max-width: 100%;
  margin-top: 5em;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 5em;
}

.gallery {
  max-width: 100%;
  margin: 0 auto;
  animation: fader 30s linear infinite;
  height: 500px;
}

这会创建图像库并每隔几秒钟交换一次图像,但我无法弄清楚如何让每个图像在切换到下一个图像时淡化,或者如何为图像设置动画以便它在显示时向上浮动。

我怎样才能做到这一点?我可以对同一个元素应用多个关键帧吗?如果有帮助,这里是 CodeSandbox。

标签: cssimagecarouselcss-animationskeyframe

解决方案


我不是 100% 确定您所说的“为图像设置动画,以便在显示时向上浮动”,但我可以与您分享我用来让图像淡入和淡出的关键帧。我希望这对你有帮助。您可以将 CSS 类应用于该部分内容,或使用您喜欢的方法来建立此关键帧。一旦你设置了淡入淡出动画,假设这不是幻灯片,并且图像只是在一段时间后淡入淡出加载。

 @keyframes fadeinout {
    0%   { opacity:1; }
    17%  { opacity:1; }
    25%  { opacity:0; }
    92%  { opacity:0; }
    100% { opacity:1; }
}

我注意到这个问题的标题是“将图像淡入另一个”,如果您的意思是一个图像变为另一个图像(在 CSS 中,我们的意思是这组图像将在 position:absolute;,您需要设置 :nth-of-type(n) 选择器以在子级上设置动画延迟。因此,如果您有一组 3 张图像想要淡出,您可以使用下面的。

#slideshow img:nth-of-type(1) {
    -webkit-animation-delay: 6s;
    -moz-animation-delay: 6s;
    -o-animation-delay: 6s;
    animation-delay: 6s;
}
#slideshow img:nth-of-type(2) {
    -webkit-animation-delay: 4s;
    -moz-animation-delay: 4s;
    -o-animation-delay: 4s;
    animation-delay: 4s;
}
#slideshow img:nth-of-type(3) {
    -webkit-animation-delay: 2s;
    -moz-animation-delay: 2s;
    -o-animation-delay: 2s;
    animation-delay: 2s;
}

推荐阅读