且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript图片幻灯片

更新时间:2023-02-14 08:49:14

关于如何遍历数组的非常基本且简单的示例

A very basic and simple example of how you can step through an array

//Array of images
var Images = ['https://dummyimage.com/100x100/000/fff.jpg',
  'https://dummyimage.com/200x200/000/fff.jpg',
  'https://dummyimage.com/300x300/000/fff.jpg'
];
//Step counter
var step = 1;

function gallery() {
  //change image
  document.getElementById('Imgs').src = Images[step];
  //Or you can use - document.images.slide.src=Images[step];
  // is step more than the image array?
  if (step < Images.length - 1) {
    // No - add 1 for next image.
    step++;
  } else {
    // Yes - Start from the first image
    step = 0;
  }
}
//When the ready, set interval.
window.onload = setInterval(gallery, 2500);

<img id="Imgs" name="slide" src="https://dummyimage.com/100x100/000/fff.jpg" />

您尝试的方法将在浏览器控制台中返回以下错误.

The method you're trying will return the following errors in the browser console.

未捕获的ReferenceError:图片未定义(匿名函数)

Uncaught ReferenceError: image is not defined(anonymous function)

未捕获的TypeError:无法读取未定义的属性'src'

Uncaught TypeError: Cannot read property 'src' of undefined

在使用javascript时,浏览器控制台是您***的朋友.

如果您有任何疑问,请在下面发表评论,我们会尽快与您联系.

If you have any questions, please leave a comment below and I will get back to you as soon as possible.

如果您要使用相同的方法,那就是:

If you want to stick with the same method here it is:

var step = 1;
var image1 = new Image();
image1.src = "https://dummyimage.com/100x100/000/fff.jpg";
var image2 = new Image();
image2.src = "https://dummyimage.com/200x200/000/fff.jpg";
var image3 = new Image();
image3.src = "https://dummyimage.com/300x300/000/fff.jpg";

function slideit() {
  document.images.slide.src = window['image' + step].src;
  if (step < 3)
    step++;
  else
    step = 1;
  setTimeout(slideit, 2500);
}
slideit();

<div class="row">
  <div class="col-md-12">
    <h3 class="Contains">
      <img src="https://dummyimage.com/100x100/000/fff.jpg" name="slide" />
    </h3>
  </div>

我希望这会有所帮助.编码愉快!

I hope this helps. Happy coding!