首页 > 解决方案 > 带淡入的 CSS 图像滑块

问题描述

我一直在尝试创建一个简单的图像滑块,展示一个网站的四个图像。我已经设法创建了幻灯片,但是每个图像之间的过渡非常快,我想要一点淡入效果,以便它更平滑。这里的很多问题已经建议使用 jQuery,但我正在尝试只使用 CSS。我也探索了 animate.css 但无法让它工作。感谢提供的任何/所有帮助。谢谢 :)

到目前为止的代码如下:

HTML

   <div class="slider">
      <div class="feature">
      </div>
      <div class="overlay">

      </div>
   </div>

和 CSS

.feature {
   animation: slide 3s;

}

.slider {
   background-repeat: no-repeat;
   background-size: cover;
   width: 100%;
   height: 80vh;
   animation: slide 10s infinite;
}

.overlay {
   color: #fff;
   width: 100%;
   height: 80vh;
   background-color: rgba(0, 0, 0, 0.5);
}



@keyframes slide {
   0%{
      background-image: url(../resources/feature/Feature1.jpg);
   }

   25%{
      background-image: url(../resources/feature/Feature1.jpg);
   }

   25.1%{
      background-image: url(../resources/feature/Feature2.jpg);
   }

   50%{
      background-image: url(../resources/feature/Feature2.jpg);
   }
   50.01%{
      background-image: url(../resources/feature/Feature3.jpg);
   }

   75%{
      background-image: url(../resources/feature/Feature3.jpg);
   }

   75.01%{
      background-image: url(../resources/feature/Feature4.jpg);
   }

   100%{
      background-image: url(../resources/feature/Feature4.jpg);
   }
}

标签: cssanimationsliderslideshowfadein

解决方案


您必须设置“滑块”的opacityandtransition才能获得效果。

.feature {

}

.slider {
   background-repeat: no-repeat;
   background-size: cover;
   width: 100%;
   height: 80vh;
   transition: all .2s ease-in-out;
   animation: slide 10s infinite;
}

.overlay {
   color: #fff;
   width: 100%;
   height: 80vh;
   background-color: rgba(0, 0, 0, 0.5);
   transition: all .2s ease-in-out;
}



@keyframes slide {
   0%{
      opacity: 0;
      background-color: red;
   }

   20%{
   opacity: 1;
      background-color: red;
   }
   25%{
   opacity: 0;
      background-color: red;
   }
   25.1%{
   opacity: 0;
      background-color: blue;
   }

   45%{
   opacity: 1;
      background-color: blue;
   }
   50%{
   opacity: 0;
      background-color: blue;
   }
   50.01%{
   opacity: 0;
      background-color: yellow;
   }

   70%{
   opacity: 1;
      background-color: yellow;
   }
   75%{
   opacity: 0;
      background-color: yellow;
   }

   75.01%{
   opacity: 0;
      background-color: green;
   }

   95%{
   opacity: 1;
      background-color: green;
   }
   100%{
   opacity: 0;
      background-color: green;
   }
}
<div class="slider">
      <div class="feature">
      </div>
      <div class="overlay">

      </div>
   </div>


推荐阅读