Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 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 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...