js 面向对象实现自动轮播
时间: 2023-10-16 11:11:08 浏览: 56
以下是一个js面向对象实现自动轮播的示例代码:
```javascript
// 定义轮播图类
class Slider {
constructor(container, options = {}) {
this.container = container;
this.slides = container.querySelectorAll('.slide');
this.currentSlide = 0;
this.interval = options.interval || 3000; // 自动轮播间隔时间
this.pauseOnHover = options.pauseOnHover || false; // 鼠标悬停暂停自动轮播
this.timerId = null;
// 绑定事件
if (this.pauseOnHover) {
this.container.addEventListener('mouseover', this.pause.bind(this));
this.container.addEventListener('mouseout', this.play.bind(this));
}
}
// 自动轮播
play() {
this.timerId = setInterval(() => {
this.showSlide(this.currentSlide + 1);
}, this.interval);
}
// 暂停自动轮播
pause() {
clearInterval(this.timerId);
}
// 显示指定的轮播项
showSlide(index) {
this.slides[this.currentSlide].classList.remove('active');
this.currentSlide = (index + this.slides.length) % this.slides.length;
this.slides[this.currentSlide].classList.add('active');
}
}
// 使用示例
const sliderContainer = document.querySelector('.slider');
const slider = new Slider(sliderContainer, {
interval: 4000,
pauseOnHover: true,
});
slider.play(); // 启动自动轮播
```
其中,`Slider`类的构造函数接收两个参数:轮播图容器和配置选项。配置选项包括自动轮播间隔时间和鼠标悬停暂停自动轮播等。`play`方法用于启动自动轮播,`pause`方法用于暂停自动轮播,`showSlide`方法用于显示指定的轮播项。在构造函数中,可以根据配置选项绑定鼠标悬停事件,实现鼠标悬停暂停自动轮播功能。在使用示例中,创建`Slider`实例后,调用`play`方法启动自动轮播。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)