首页 > 解决方案 > 我怎样才能重复这个循环的幻灯片,以便在到达最后一个元素时再次播放

问题描述

基本上,我知道必须使用像 count 这样的变量来存储数组中元素的原始数量,但它应该附加到循环的部分尚不清楚。任何帮助都意义重大。谢谢!

        let slider = document.getElementById('slider');
        const imagesArray = [
       'https://images.pexels.com/photos/572897/pexels-photo-572897.jpeg? auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
       'https://images.pexels.com/photos/2832039/pexels-photo-2832039.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940',
       'https://images.pexels.com/photos/2574643/pexels-photo-2574643.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940'
       ]

       let count = 0; //I know that we need this, but can't think of attaching it to the array somehow.
       imagesArray.forEach((image, i) => {
       window.setTimeout(() => {
         slider.style.backgroundImage = `url(${image})`;
       }, 1000 * i);
       });
#slider{
  width:auto;
  height:300px;
  margin:16px;
  background-size:cover;
  background-repeat:none;
}
<div id="slider"></div>

标签: javascript

解决方案


不要在循环中创建images.length超时,而是定义一个显示“当前”图像并设置超时以显示下一个图像的函数。

然后很容易将其修改为“环绕”到开头:

function showNext(i) {
  if (i === imagesArray.length) {
    i = 0; // wrap around
  }
  slider.style.backgroundImage = `url(${imagesArray[i]})`;
  
  setTimeout(() => showNext(i+1), 1000)
}

showNext(0); // start

如果您想从头开始重新启动,您的循环方法将不起作用,因为它明确表示“为数组中的每个元素执行一次”。


推荐阅读