Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

html - cross fading 2 elements to creat a looping animation with no js

I am wanting to animate an element so it cycles between "0% interest free credit" and "free delivery", I am trying to achieve this with no javascript, but I am only able to get the first element to fade away and not get the second to fade in.

.parent {
  position: relative;
}

.parent p {
  position: absolute;
  top: 0;
  left: 0;
}

.parent p:first-child {
  animation: hide 2s ease-in
}

.parent p:last-child {
  opacity: 0;
  animation: show 2s ease-in animation-delay:2s;
}

@keyframes show {
  to {
    opacity: 1;
  }
}

@keyframes hide {
  to {
    opacity: 0;
  }
}
<div class="parent">
  <p>0% interest free credit</p>
  <p>free delivery</p>
</div>
question from:https://stackoverflow.com/questions/65892844/cross-fading-2-elements-to-creat-a-looping-animation-with-no-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, you need to make sure your animation is set to loop. Use the keyword infinite as your animation-timing-function for that.

Second, we can restructure your animation to happen in one reusable keyframe sequence that shows and hides the element. By making the whole animation 4 seconds long and offsetting it by half of that (2 seconds) on one element, we achieve a seamless loop of the two elements fading in and out:

.parent {
  position: relative;
}

.parent p {
  animation: show 4s infinite;
  position: absolute;
  top: 0;
  left: 0;
}

.parent p:last-child {
  animation-delay: -2s;
}

@keyframes show {
  0%, 50%, 100% {
    opacity: 0;
  }
  
  10%, 40% {
    opacity: 1;
  }
}
<div class="parent">
  <p>0% interest free credit</p>
  <p>free delivery</p>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...