css 如何显示下一个图像下当前一个在这个自动旋转滑块?

ff29svar  于 2023-03-20  发布在  其他
关注(0)|答案(1)|浏览(156)

我正在尝试做一个无限自动播放旋转木马,全屏使用香草JS。我正在使用数组来存储图像。恼人的是,当图像幻灯片有一个平原背景,我想看到下一个图像。
我试过在CSS文件中设置2个背景图片,但是没有效果。有什么帮助吗?
在我的本地计算机上,转盘从数组中旋转3。目前它只显示“images[0]”。不确定原因。

// carousel gallery

const images = ["DSC02663.jpg", "DSC02664.jpg", "DSC02665.jpg"];

const carousel = document.querySelector(".slider");

const interval = setInterval(function () {
    startCarousel();
}, 5000);

function startCarousel() {
    let index = 0;
    let currentImage = `url(https://raw.githubusercontent.com/rossivk/ipc/main/assets/images/${images[index]})`;
    carousel.style.backgroundImage = currentImage;
  
    carousel.classList.remove("slide");
    void carousel.offsetWidth;
    carousel.classList.add("slide")

    let newLastElement = images.shift();
    images.push(newLastElement);
}
.slider {
    width: 100vw;
    height: 100vh;
    background-position: center;
    background-size: cover;
    background-image: url(https://raw.githubusercontent.com/rossivk/ipc/main/assets/images/DSC02663.jpg);
}

.slide {
    -webkit-animation: 1.5s slide;
    animation: 5s slide;
}

@-webkit-keyframes slide {
    from {
        transform: translateX(0);
    }

    to {
        transform: translateX(-100vw);
    }
}

@keyframes slide {
    from {
        transform: translateX(0);
    }

    to {
        transform: translateX(-100vw);
    }
}
<div class="slider slide">
    </div>
2w3kk1z5

2w3kk1z51#

当你设置carousel.style.backgroundImage时,你需要add url() to the string。同时考虑重新排序初始数组,这样第一个图像就不会重复:

// carousel gallery

const images = [ "DSC02664.jpg", "DSC02665.jpg","DSC02663.jpg"];

const carousel = document.querySelector(".slider");

const interval = setInterval(function () {
    startCarousel();
}, 5000);

function startCarousel() {
    let index = 0;
    let currentImage = `url(https://raw.githubusercontent.com/rossivk/ipc/main/assets/images/${images[index]})`;
    carousel.style.backgroundImage = currentImage;
  
    carousel.classList.remove("slide");
    void carousel.offsetWidth;
    carousel.classList.add("slide")

    let newLastElement = images.shift();
    images.push(newLastElement);
}
.slider {
    width: 100vw;
    height: 100vh;
    background-position: center;
    background-size: cover;
    background-image: url(https://raw.githubusercontent.com/rossivk/ipc/main/assets/images/DSC02663.jpg);
}

.slide {
    -webkit-animation: 1.5s slide;
    animation: 5s slide;
}

@-webkit-keyframes slide {
    from {
        transform: translateX(0);
    }

    to {
        transform: translateX(-100vw);
    }
}

@keyframes slide {
    from {
        transform: translateX(0);
    }

    to {
        transform: translateX(-100vw);
    }
}
<div class="slider slide">
    </div>

相关问题