首页 > 解决方案 > 使用 CSS 关键帧的内容在彼此之上的无限动画

问题描述

我有以下HTMLCSS代码:

.parent{
 height: 10%;
 width: 100%;
 float: left;
 position: relative;
}
 
.content1{
 height: 100%;
 width: 20%;
 background-color: blue;
 float: left;
 position: absolute;
}
 
 .content2{
 height: 100%;
 width: 20%;
 background-color: red;
 float: left;
 animation-delay: 1s;
  position: absolute;
}
 
 .content3{ 
 height: 100%;
 width: 20%;
 background-color:yellow;
 float: left;
 animation-delay: 2s;
 position: absolute;
}
 
.content4{
 height: 100%;
 width: 20%;	
 background-color: green;
 float: left;
 animation-delay: 3s;
 position: absolute;
}
 
 .content5{
 height: 100%;
 width: 20%;
 background-color: orange;
 float: left;
 animation-delay: 4s;
}
 
 
.parent div {
 animation-name: animation_01;
 animation-duration:2s;
 animation-iteration-count:infinite;
 animation-fill-mode: forwards;
 opacity:0;
 }


@keyframes animation_01 {
  0% {
    opacity: 0
  }
  50% {
    opacity: 1
  }
  100% {
    opacity: 0
  }
}
<div class="parent">
	<div class="content1">Here goes content1</div>
	<div class="content2">Here goes content2</div>
	<div class="content3">Here goes content3</div>
	<div class="content4">Here goes content4</div>
	<div class="content5">Here goes content5</div>
 </div>

keyframes正如您在代码中看到的那样,我通过使用动画将 5 个内容相互叠加显示。我想无限运行这个动画,所以我放了animation-iteration-count:infinite;.

但是,一旦动画到达content5,它就不会返回content1并重新开始。相反,它只会返回content4然后显示/隐藏content4content5处于无限循环中。

我必须在我的代码中更改什么,以便动画返回content1并重新开始动画?

标签: htmlcsscss-animationskeyframe

解决方案


定义更长的动画。

此示例中的动画持续时间为 5 秒,可见时间范围为 2 秒。每个 div 都有不同的延迟,因此当一个 div 淡出时,另一个开始淡入。

.parent {
  height: 10%;
  width: 100%;
  float: left;
  position: relative;
}

.parent div {
  animation-name: animation_01;
  animation-duration: 5s;
  animation-iteration-count: infinite;
  opacity: 0;
}

.content1 {
  height: 100%;
  width: 20%;
  background-color: blue;
  position: absolute;
  opacity: 1;
}

.content2 {
  height: 100%;
  width: 20%;
  background-color: red;
  animation-delay: 1s;
  position: absolute;
}

.content3 {
  height: 100%;
  width: 20%;
  background-color: yellow;
  animation-delay: 2s;
  position: absolute;
}

.content4 {
  height: 100%;
  width: 20%;
  background-color: green;
  animation-delay: 3s;
  position: absolute;
}

.content5 {
  height: 100%;
  width: 20%;
  background-color: orange;
  animation-delay: 4s;
}

.parent {}

@keyframes animation_01 {
  20% {
    opacity: 1
  }
  0%, 40% , 100% {
    opacity: 0
  }
}


}
<div class="parent">
  <div class="content1">Here goes content1</div>
  <div class="content2">Here goes content2</div>
  <div class="content3">Here goes content3</div>
  <div class="content4">Here goes content4</div>
  <div class="content5">Here goes content5</div>
</div>


推荐阅读