使用CSS关键帧在内容之上无限播放动画

时间:2018-11-19 13:51:07

标签: html css css-animations keyframe

我有以下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并重新开始动画?

1 个答案:

答案 0 :(得分:3)

定义更长的动画。

此示例中的动画持续时间为5秒,可见时间段为2秒。每个div都有不同的延迟,因此当一个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>