77 lines
2.4 KiB
JavaScript
77 lines
2.4 KiB
JavaScript
|
|
document.addEventListener("DOMContentLoaded", function() {
|
||
|
|
// 获取所有轮播图容器
|
||
|
|
const carousels = document.querySelectorAll('.image-carousel');
|
||
|
|
|
||
|
|
carousels.forEach(carousel => {
|
||
|
|
const slides = carousel.querySelectorAll('.carousel-slide');
|
||
|
|
const prevBtn = carousel.querySelector('.carousel-prev');
|
||
|
|
const nextBtn = carousel.querySelector('.carousel-next');
|
||
|
|
const dots = carousel.querySelectorAll('.carousel-dot');
|
||
|
|
let currentIndex = 0;
|
||
|
|
|
||
|
|
// 显示特定索引的幻灯片
|
||
|
|
function showSlide(index) {
|
||
|
|
// 隐藏所有幻灯片
|
||
|
|
slides.forEach(slide => {
|
||
|
|
slide.style.display = 'none';
|
||
|
|
});
|
||
|
|
|
||
|
|
// 移除所有圆点的active类
|
||
|
|
dots.forEach(dot => {
|
||
|
|
dot.classList.remove('active');
|
||
|
|
});
|
||
|
|
|
||
|
|
// 显示当前幻灯片
|
||
|
|
slides[index].style.display = 'block';
|
||
|
|
|
||
|
|
// 确保导航按钮总是可见
|
||
|
|
if (prevBtn) prevBtn.style.display = 'flex';
|
||
|
|
if (nextBtn) nextBtn.style.display = 'flex';
|
||
|
|
|
||
|
|
// 给当前圆点添加active类
|
||
|
|
if (dots.length > 0 && index < dots.length) {
|
||
|
|
dots[index].classList.add('active');
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// 显示初始幻灯片
|
||
|
|
showSlide(currentIndex);
|
||
|
|
|
||
|
|
// 前一张按钮点击事件
|
||
|
|
if (prevBtn) {
|
||
|
|
prevBtn.addEventListener('click', (e) => {
|
||
|
|
e.stopPropagation(); // 阻止事件冒泡
|
||
|
|
currentIndex = currentIndex > 0 ? currentIndex - 1 : slides.length - 1;
|
||
|
|
showSlide(currentIndex);
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
// 下一张按钮点击事件
|
||
|
|
if (nextBtn) {
|
||
|
|
nextBtn.addEventListener('click', (e) => {
|
||
|
|
e.stopPropagation(); // 阻止事件冒泡
|
||
|
|
currentIndex = currentIndex < slides.length - 1 ? currentIndex + 1 : 0;
|
||
|
|
showSlide(currentIndex);
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
// 圆点点击事件
|
||
|
|
dots.forEach((dot, index) => {
|
||
|
|
dot.addEventListener('click', () => {
|
||
|
|
currentIndex = index;
|
||
|
|
showSlide(currentIndex);
|
||
|
|
});
|
||
|
|
});
|
||
|
|
|
||
|
|
// 可选:键盘导航
|
||
|
|
document.addEventListener('keydown', (e) => {
|
||
|
|
if (e.key === 'ArrowLeft') {
|
||
|
|
currentIndex = currentIndex > 0 ? currentIndex - 1 : slides.length - 1;
|
||
|
|
showSlide(currentIndex);
|
||
|
|
} else if (e.key === 'ArrowRight') {
|
||
|
|
currentIndex = currentIndex < slides.length - 1 ? currentIndex + 1 : 0;
|
||
|
|
showSlide(currentIndex);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
});
|
||
|
|
});
|