使用构造函数以及原型的方法实现图片轮播
时间: 2023-05-30 07:07:51 浏览: 140
以下是一个使用构造函数以及原型的方法实现图片轮播的示例代码:
```javascript
function Slider(elementId, images) {
this.element = document.getElementById(elementId);
this.images = images;
this.currentIndex = 0;
this.intervalId = null;
}
Slider.prototype.start = function() {
this.showImage();
this.intervalId = setInterval(this.showImage.bind(this), 3000);
};
Slider.prototype.showImage = function() {
var imageUrl = this.images[this.currentIndex];
this.element.style.backgroundImage = 'url(' + imageUrl + ')';
this.currentIndex = (this.currentIndex + 1) % this.images.length;
};
var images = [
'http://example.com/image1.jpg',
'http://example.com/image2.jpg',
'http://example.com/image3.jpg'
];
var slider = new Slider('slider', images);
slider.start();
```
这个示例代码中,`Slider` 构造函数接收两个参数:要轮播的元素的 ID 和图片的数组。它还定义了一些属性,例如当前显示的图片的索引以及定时器的 ID。`start` 方法用于开始轮播,并在每个 3 秒钟显示下一张图片。`showImage` 方法用于显示当前索引对应的图片,并将索引递增以准备显示下一张图片。
在最后,我们创建了一个 `Slider` 实例,并调用它的 `start` 方法开始轮播。
阅读全文
相关推荐















