帮我用原生JS写一个带缩略图的轮播图
时间: 2023-03-04 22:53:37 浏览: 108
好的,以下是一个使用原生JS实现带缩略图的轮播图的示例代码:
HTML部分:
```
<div class="slider">
<div class="slides">
<div class="slide"><img src="image1.jpg"></div>
<div class="slide"><img src="image2.jpg"></div>
<div class="slide"><img src="image3.jpg"></div>
<div class="slide"><img src="image4.jpg"></div>
</div>
<div class="thumbnails"></div>
</div>
```
CSS部分:
```
.slider {
position: relative;
overflow: hidden;
}
.slides {
display: flex;
transition: transform 0.3s ease-in-out;
}
.slide {
flex: 0 0 100%;
}
.slide img {
width: 100%;
height: auto;
}
.thumbnails {
display: flex;
justify-content: center;
margin-top: 10px;
}
.thumbnail {
flex: 0 0 auto;
margin-right: 10px;
}
.thumbnail img {
width: 100%;
height: auto;
opacity: 0.5;
cursor: pointer;
}
.thumbnail img.active {
opacity: 1;
}
```
JS部分:
```
const slider = document.querySelector('.slider');
const slides = slider.querySelector('.slides');
const slideWidth = slider.clientWidth;
const thumbnails = slider.querySelector('.thumbnails');
let slideIndex = 0;
function showSlide(index) {
slides.style.transform = `translateX(-${slideWidth * index}px)`;
thumbnails.querySelector('.active').classList.remove('active');
thumbnails.querySelectorAll('.thumbnail')[index].querySelector('img').classList.add('active');
}
function nextSlide() {
slideIndex = (slideIndex + 1) % slides.children.length;
showSlide(slideIndex);
}
function initThumbnails() {
for (let i = 0; i < slides.children.length; i++) {
const thumbnail = document.createElement('div');
thumbnail.classList.add('thumbnail');
const thumbnailImg = document.createElement('img');
thumbnailImg.src = slides.children[i].querySelector('img').src;
thumbnailImg.addEventListener('click', () => {
slideIndex = i;
showSlide(slideIndex);
});
thumbnail.appendChild(thumbnailImg);
thumbnails.appendChild(thumbnail);
}
thumbnails.querySelectorAll('.thumbnail')[slideIndex].querySelector('img').classList.add('active');
}
initThumbnails();
setInterval(nextSlide, 5000);
```
这段代码实现了一个基本的轮播图,其中每张图片都有一个对应的缩略图,点击缩略图可以切换到对应的图片。轮播图会自动切换,每5秒自动播放下一张图片。请注意,这只是一个简单的示例代码,可能需要根据实际需求进行修改和调整。
阅读全文