为什么此幻灯片中图像的不透明度没有改变? (CSS, Javascript)

Why is the opacity not changing for images in this slideshow? (CSS, Javascipt)

我正在尝试构建图像轮播。但是,我 运行 出现了不透明 animation/transition.

的意外行为

我有一个 .active class 在三个 img 之间成功转换。这 .active class 添加 opacity: 1;。然而,当最后一个 img 加载到 DOM 时,它保留了它的初始 opacity: 0;,即使 .active class 被添加到每个 img 每六秒,opacity 不变。

我想这可能是一个 CSS 问题,但非常感谢您的帮助!

Javascript

    const autoSlideshow = () => {
        const slides = document.querySelectorAll('.slides img')
        const slideDelay = 6000
        let currentSlide = 0
    
        slides[currentSlide].classList.add('.active')
    
        const nextSlide = () => {
            slides[currentSlide].classList.remove('.active')
            currentSlide = (currentSlide + 1) % slides.length
            slides[currentSlide].classList.add('.active')
        }
    
        setInterval(nextSlide, slideDelay)
    }
    autoSlideshow()

CSS

.slides img.active {
    opacity: 1;
    transition: opacity 2s ease-in-out;
}
.slides img {
    position: inherit;
    width: 100%;
    height: 100%;
    object-fit: cover;
    opacity: 0;
}

HTML

<div class="slides">
   <img src="img/ac62.jpg" alt="couple 1"> 
   <img src="img/b348.jpg" alt="couple 2">
   <img src="img/bk40.jpg" alt="couple 3">
</div>

解决方案

const autoSlideshow = () => {
    const slides = document.querySelectorAll('.slides img')
    const slideDelay = 6000
    let currentSlide = 0

    slides[currentSlide].classList.add('active')

    const nextSlide = () => {
        slides[currentSlide].classList.remove('active')
        currentSlide = (currentSlide + 1) % slides.length
        slides[currentSlide].classList.add('active')
    }

    setInterval(nextSlide, slideDelay)
}
autoSlideshow()

.active替换为active

您需要从 .active 中删除 .,同时在 class 列表中添加或删除。因为你已经在做classList.add/classList.remove,所以没必要用.

定义一个class

const autoSlideshow = () => {
        const slides = document.querySelectorAll('.slides img')
        const slideDelay = 6000
        let currentSlide = 0
    
        slides[currentSlide].classList.add('active')
    
        const nextSlide = () => {
            slides[currentSlide].classList.remove('active')
            currentSlide = (currentSlide + 1) % slides.length
            slides[currentSlide].classList.add('active')
        }
    
        setInterval(nextSlide, slideDelay)
    }
    autoSlideshow()
.slides img.active {
    opacity: 1;
    transition: opacity 2s ease-in-out;
}
.slides img {
    position: inherit;
    width: 100%;
    height: 100%;
    object-fit: cover;
    opacity: 0;
}
<div class="slides">
   <img src="https://source.unsplash.com/random" alt="couple 1"> 
   <img src="https://source.unsplash.com/random" alt="couple 2">
   <img src="https://source.unsplash.com/random" alt="couple 3">
</div>