请用js原生封装一个轮播图案例
时间: 2024-01-15 17:04:54 浏览: 174
原生js实现无缝轮播图效果
好的,以下是一个基于原生JS实现的轮播图案例:
HTML部分:
```html
<div class="slider">
<div class="slider-wrapper">
<img src="image1.jpg">
<img src="image2.jpg">
<img src="image3.jpg">
</div>
<div class="slider-dots">
<span class="dot active"></span>
<span class="dot"></span>
<span class="dot"></span>
</div>
</div>
```
CSS部分:
```css
.slider {
position: relative;
overflow: hidden;
}
.slider-wrapper {
display: flex;
transition: transform 0.5s ease-out;
}
.slider-wrapper img {
width: 100%;
height: auto;
}
.slider-dots {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
display: flex;
}
.slider-dots .dot {
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #ccc;
margin-right: 10px;
cursor: pointer;
}
.slider-dots .active {
background-color: #333;
}
```
JS部分:
```js
const slider = document.querySelector('.slider');
const wrapper = slider.querySelector('.slider-wrapper');
const images = wrapper.querySelectorAll('img');
const dots = slider.querySelectorAll('.dot');
let currentImage = 0;
let interval;
function startSlider() {
interval = setInterval(() => {
currentImage++;
if (currentImage >= images.length) {
currentImage = 0;
}
goToImage(currentImage);
}, 3000);
}
function goToImage(index) {
wrapper.style.transform = `translateX(-${index * 100}%)`;
updateDots(index);
}
function updateDots(index) {
dots.forEach(dot => {
dot.classList.remove('active');
});
dots[index].classList.add('active');
}
dots.forEach((dot, index) => {
dot.addEventListener('click', () => {
currentImage = index;
goToImage(currentImage);
clearInterval(interval);
startSlider();
});
});
startSlider();
```
这个轮播图实现了自动播放和手动切换图片的功能,并且可以根据当前显示的图片来更新底部的小圆点。
阅读全文