.carousel {
position: relative;
width: 600px;
height: 400px;
overflow: hidden;
margin: 0 auto;
}
.carousel-inner {
display: flex;
width: 100%;
height: 100%;
transition: transform 0.5s ease;
}
.carousel-item {
min-width: 100%;
height: 100%;
}
.carousel-item img {
width: 100%;
height: 100%;
object-fit: cover;
}
.carousel-item:not(.active) {
display: none;
}
.carousel-prev, .carousel-next {
position: absolute;
top: 50%;
transform: translateY(-50%);
background: rgba(0,0,0,0.5);
color: white;
border: none;
padding: 10px;
cursor: pointer;
}
.carousel-prev { left: 10px; }
.carousel-next { right: 10px; }
.carousel-indicators {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 8px;
}
.carousel-indicators span {
width: 12px;
height: 12px;
background: #ccc;
border-radius: 50%;
cursor: pointer;
}
.carousel-indicators span.active {
background: white;
}
class Carousel {
constructor(container) {
this.container = document.querySelector(container);
this.items = this.container.querySelectorAll('.carousel-item');
this.indicators = this.container.querySelectorAll('.carousel-indicators span');
this.prevBtn = this.container.querySelector('.carousel-prev');
this.nextBtn = this.container.querySelector('.carousel-next');
this.currentIndex = 0;
this.interval = null;
this.autoPlayInterval = 3000; // 自动播放间隔
this.init();
// 显示当前项
this.items[index].classList.add('active');
this.indicators[index].classList.add('active');this.prevBtn.addEventListener('click', () => {
this.prev();
this.resetAutoPlay();
});
this.indicators.forEach((indicator, index) => {
indicator.addEventListener('click', () => {
this.currentIndex = index;
this.showItem(index);
this.resetAutoPlay();
});
});
// 悬停时暂停自动播放
this.container.addEventListener('mouseenter', () => this.pauseAutoPlay());
this.container.addEventListener('mouseleave', () => this.startAutoPlay());