为什么这个淡入淡出的幻灯片动画不能完全正常工作?

Why this fading slideshow animation is not fully working?

我无法让此幻灯片在每个 img 中都正常工作。

调整了几个小时后,我得出的结论是问题与时间和 类 同时交换所有元素有关,但我找不到解决问题的方法.

let slideIndexPrev = 1;
let slideIndexCurr = 0;

showSlides();

function showSlides() {
  let slides = document.getElementsByClassName("mySlides");

  
  if (slideIndexPrev >= slides.length) {slideIndexPrev = 0}
  if (slideIndexCurr >= slides.length) {slideIndexCurr = 0}
  
  slides[slideIndexCurr].classList.add("fade-in");
  slides[slideIndexCurr].classList.remove("fade-out");
  slides[slideIndexPrev].classList.add("fade-out");
  slides[slideIndexPrev].classList.remove("fade-in");
  
  slideIndexPrev++;
  slideIndexCurr++;

  setTimeout(showSlides, 3000); // Change image every X seconds
}
* {box-sizing:border-box}

/* Slideshow container */
.slideshow-container {
  display: flex;
  position: relative;
  min-width: 100%;
  min-height: 250px;
  border-bottom: 2px solid #333;
}
.mySlides img {
  display: flex;
  position: absolute;
  width: 100%; 
  height: 100%; 
  object-fit: cover;
}

/* Fading animation */
.fade-in {
  animation-name: fade-in;
  animation-duration: 2s;
}
.fade-out {
  animation-name: fade-out;
  animation-duration: 2s;
}

@keyframes fade-in {
  from {opacity: 0}
  to   {opacity: 1}
}
 
@keyframes fade-out {
  from {opacity: 1}
  to   {opacity: 0}
}
  <!-- Slideshow container -->
        <div class="slideshow-container">
            <!-- Full-width images -->
            <div class="mySlides">
                <img src="https://ca-   times.brightspotcdn.com/dims4/default/f652f70/2147483647/strip/true/crop/5389x3153+0+0/resize/1486x869!/quality/90/?url=https%3A%2F%2Fcalifornia-times-brightspot.s3.amazonaws.com%2Fa9%2F5b%2Fc621f3bc408e95c16b4538d87578%2Fla-photos-1staff-amazonstudios-210802a.jpg" 
                    style="object-position: 50% 40%;">
            </div>
            <div class="mySlides">
                <img src="https://i.pinimg.com/originals/c5/6b/d1/c56bd1d016ccd315aa9e8d3ec3c78bb7.png" 
                    style="object-position: 50% 47%;">        
            </div>
            <div class="mySlides">
                <img src="https://wallpaperaccess.com/full/3203467.jpg" 
                    style="object-position: 50% 51%;">
        </div>

在此先感谢您提供的任何帮助!

  1. 您目前有两个元素 fade-in 和一个 fade-out - 查看控制台。所以你可能想把 js 中的那些交换成这样:
    slides[slideIndexCurr].classList.add("fade-out");
    slides[slideIndexCurr].classList.remove("fade-in");
    slides[slideIndexPrev].classList.add("fade-in");
    slides[slideIndexPrev].classList.remove("fade-out");
  1. 当动画结束时,不透明度又回到1。所以它变淡,然后突然重新出现。只需将 opacity: 0; 添加到您的 fade-out class.

见笔: https://codepen.io/rajniszp/pen/RwQpmZR

如果我有帮助,请投票:D