前端写一个带缩略图的轮播图
时间: 2024-01-20 08:03:47 浏览: 32
好的,以下是一个简单的前端带缩略图的轮播图实现示例:
HTML代码:
```html
<div class="carousel-container">
<div class="carousel">
<img src="img1.jpg" alt="Image 1">
<img src="img2.jpg" alt="Image 2">
<img src="img3.jpg" alt="Image 3">
<img src="img4.jpg" alt="Image 4">
<img src="img5.jpg" alt="Image 5">
</div>
<div class="thumbnails">
<img src="img1.jpg" alt="Thumbnail 1">
<img src="img2.jpg" alt="Thumbnail 2">
<img src="img3.jpg" alt="Thumbnail 3">
<img src="img4.jpg" alt="Thumbnail 4">
<img src="img5.jpg" alt="Thumbnail 5">
</div>
</div>
```
CSS代码:
```css
.carousel-container {
position: relative;
width: 800px;
height: 400px;
}
.carousel {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
.carousel img {
display: none;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.carousel img:first-child {
display: block;
}
.thumbnails {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 80px;
background-color: #ddd;
display: flex;
justify-content: center;
align-items: center;
padding: 10px;
}
.thumbnails img {
width: 60px;
height: 60px;
margin: 0 10px;
border: 2px solid #fff;
cursor: pointer;
opacity: 0.5;
}
.thumbnails img.active {
opacity: 1;
}
```
JavaScript代码:
```javascript
var carousel = document.querySelector('.carousel');
var thumbnails = document.querySelector('.thumbnails');
var images = document.querySelectorAll('.carousel img');
var thumbs = document.querySelectorAll('.thumbnails img');
var currentIndex = 0;
var intervalId;
// 切换轮播图
function switchCarousel(index) {
images[currentIndex].style.display = 'none';
thumbs[currentIndex].classList.remove('active');
images[index].style.display = 'block';
thumbs[index].classList.add('active');
currentIndex = index;
}
// 手动切换轮播图
thumbs.forEach(function(thumb, index) {
thumb.addEventListener('click', function() {
clearInterval(intervalId);
switchCarousel(index);
intervalId = setInterval(function() {
var nextIndex = currentIndex < images.length - 1 ? currentIndex + 1 : 0;
switchCarousel(nextIndex);
}, 3000);
});
});
// 自动切换轮播图
intervalId = setInterval(function() {
var nextIndex = currentIndex < images.length - 1 ? currentIndex + 1 : 0;
switchCarousel(nextIndex);
}, 3000);
```
该示例实现了一个带缩略图的轮播图,包括自动切换、手动切换和缩略图样式切换等功能。你可以根据实际需求进行相应的调整和优化。