Javascript 滑块循环

Javascript slider loop

我一直在尝试通过更改图像元素的值、使用循环遍历每个图像然后返回原始图像来为 html 创建图像滑块。

然而,一旦它到达循环的末尾,它就不会继续。

这是我的 Js 代码:

window.onload = function() {
  var x = 0
  while(x<1000){
    setTimeout(function() {
      document.getElementById('carousel').src='img/header2.jpg';
      setTimeout(function() {
        document.getElementById('carousel').src='img/header3.jpg';
        setTimeout(function() {
          document.getElementById('carousel').src='img/header.jpg';
          }, 5000);
        }, 5000);
      }, 5000);
    x = x+1
  }
}

我建议您在这种情况下不要执行 while 循环。执行时记得setTimeout

window.onload = function() {
     /* Element */
    var carousel = document.getElementById('carousel'),
     /* Carousel current image */
    cimage = 2,
     /* Carousel source images */
    csources = [
        'img/header2.jpg',
        'img/header3.jpg',
        'img/header.jpg'
    ];

    function changeCarouselImage() {
        // Reset the current image if it's ultrapassing the length - 1
        if(cimage >= 3) cimage = 0;
        // Change the source image
        carousel.src = csources[cimage ++];
        // Re-call the function after 5s
        setTimeout(changeCarouselImage, 5000);
    }

    setTimeout(changeCarouselImage, 5000);
};

最终函数没有设置另一个超时,因此动画不会继续。分成单独的功能应该会有所帮助:

var carousel = document.getElementById('carousel');

function ani1() {
    carousel.src = 'img/header.jpg';
    window.setTimeout(ani2, 500);
}

function ani2() {
    carousel.src = 'img/header2.jpg';
    window.setTimeout(ani3, 500);
}

function ani3() {
    carousel.src = 'img/header3.jpg';
    window.setTimeout(ani1, 500);
}

window.onload = ani1;