首页 > 解决方案 > 如何使用 JavaScript 制作图像轮播,与 CSS 动画同步更改照片?

问题描述

我正在尝试制作一个图像轮播,显示三张在更改时淡出和淡入的照片,但我不知道如何在与淡出淡出同步的同时使所有三张图像同时更改-在动画中。

我想我会做的是有一个包含 3 个 div 和图像的 div。然后通过js,我制作了一个包含我想要使用的所有图像的数组,然后随机选择一张照片。但是照片不能在一张幻灯片中显示两次,所以我添加了一个条件和另一个数组来检查照片是否已被使用。然后我在 5 秒后用 setInterval 交换图像,将 CSS 动画添加到主容器 div。

我也愿意接受另一种以随机顺序显示照片的方式,而不是这种方式。

完整代码:https ://srcshare.io/?id=60dd3c0ad56829604d39814b

...
               
    let waitFor = 5000;
    let imgs = document.getElementById("wrapper");

    function fadeInOut() {
                        let animation = "fade " + waitFor + "ms linear infinite";
        imgs.style.animation = animation;
    }
    function fadeStop() {

        imgs.style.animation = "";
    }

    let firstImg = document.getElementById('image1');
    let secondImg = document.getElementById('image2');
    let thirdImg = document.getElementById('image3');

    setInterval(function () {

        fadeStop();


        let imgSlots = ["", "", ""];
        let alreadyPicked = [];

        for (let i = 0; i < 3; i++) {

            let slotFull = false;

            while (!slotFull) {


                let sponsor = Math.floor(Math.random() * sponsorList.length);
                if (!alreadyPicked.includes(sponsorList[sponsor])) {

                    imgSlots[i] = sponsorList[sponsor][1];
                    alreadyPicked.push(sponsorList[sponsor]);
                    slotFull = true;
                }

            }

        }
        
            fadeInOut();
            firstImg.src = imgSlots[0];
            secondImg.src = imgSlots[1];
            thirdImg.src = imgSlots[2];

    }, waitFor);



});

</script>
<style>
  /*IMAGE CORNER CURVATURE*/
  img{
    border-radius: 0px;
   
  }
  
/*for sponsorship images*/
.inline{
  display: inline-block !important;
  width: clamp(100px,16vw,350px) !important;
  padding: 0px !important;
  white-space: nowrap !important;
  
}
  .wrapper{
    opacity: 0;
  }


@keyframes fade {
  0%,100%{opacity:0}
  15%,85%{ opacity: 1 }

}
</style>

标签: javascripthtmlcssarrayscss-animations

解决方案


推荐阅读