Crossfade two images repeatedly after showing for

2019-03-03 14:22发布

问题:

I'm trying to use HTML and CSS to crossfade two images after showing them for 10 seconds each. I want this to repeat constantly.

Here is my HTML:

<div id="container">
    <img class="bottom" src="1.png">
    <img class="top" src="2.png">
</div>

CSS:

#container {
    float: right;
    height: 246px;
    position:relative;
    width: 230px;
}

#container img {
    height: 246px;
    width: 230px;
    left:0;
    opacity: 0;
    position:absolute;
}

#container img.bottom {
    opacity: 1;
}

#container img.top {
    animation-duration: 0.1s;
    animation-name: crossFade;
    animation-iteration-count: infinite;
    animation-direction: alternate;
}

@keyframes crossFade {
    from {
        opacity: 0;
    }

    to {
        opacity: 1;
    }
}

I've never used CSS animations before so I'm a bit confused. Only the "bottom" image is being shown and nothing else happens.

What is going wrong?

回答1:

Here is an example with 10s delay and 1s animation duration.

#container {
  float: right;
  height: 246px;
  position: relative;
  width: 230px;
}
#container img {
  height: 246px;
  width: 230px;
  left: 0;
  opacity: 0;
  position: absolute;
}
#container img.bottom {
  opacity: 1;
}
#container img.top {
  -webkit-animation: crossFade 11s infinite;
  animation: crossFade 11s infinite;
  -webkit-animation-direction: alternate;
  animation-direction: alternate;
}

@-webkit-keyframes crossFade {
  0% {
    opacity: 0;
  }
  47.62% {
    opacity: 0;
  }
  52.38% {
    opacity: 1;
  }
  100% {
    opacity: 1;
  }
}
@keyframes crossFade {
  0% {
    opacity: 0;
  }
  47.62% {
    opacity: 0;
  }
  52.38% {
    opacity: 1;
  }
  100% {
    opacity: 1;
  }
}
<div id="container">
  <img class="bottom" src="https://dummyimage.com/200x200/404/fff">
  <img class="top" src="https://dummyimage.com/200x200/101/fff">
</div>