Files
bolt-website/static/js/carousel.js
2025-05-27 17:31:00 +08:00

130 lines
3.3 KiB
JavaScript

// 轮播图功能
document.addEventListener('DOMContentLoaded', function() {
const slides = document.querySelectorAll('.carousel-slide');
const indicators = document.querySelectorAll('.indicator');
const prevBtn = document.querySelector('.carousel-control.prev');
const nextBtn = document.querySelector('.carousel-control.next');
if (!slides.length) return;
let currentSlide = 0;
let slideInterval;
const slideDelay = 3000; // 3秒轮播间隔
// 初始化轮播
function startSlideshow() {
slideInterval = setInterval(nextSlide, slideDelay);
}
// 停止轮播
function stopSlideshow() {
clearInterval(slideInterval);
}
// 显示指定幻灯片
function showSlide(index) {
if (index < 0) {
index = slides.length - 1;
} else if (index >= slides.length) {
index = 0;
}
// 隐藏当前幻灯片
slides[currentSlide].classList.remove('active');
if (indicators.length) {
indicators[currentSlide].classList.remove('active');
}
// 显示新幻灯片
currentSlide = index;
slides[currentSlide].classList.add('active');
if (indicators.length) {
indicators[currentSlide].classList.add('active');
}
}
// 下一张幻灯片
function nextSlide() {
showSlide(currentSlide + 1);
}
// 上一张幻灯片
function prevSlide() {
showSlide(currentSlide - 1);
}
// 绑定指示器点击事件
if (indicators.length) {
indicators.forEach((indicator, index) => {
indicator.addEventListener('click', () => {
stopSlideshow();
showSlide(index);
startSlideshow();
});
});
}
// 绑定方向按钮点击事件
if (prevBtn) {
prevBtn.addEventListener('click', () => {
stopSlideshow();
prevSlide();
startSlideshow();
});
}
if (nextBtn) {
nextBtn.addEventListener('click', () => {
stopSlideshow();
nextSlide();
startSlideshow();
});
}
// 当鼠标悬停在轮播图上时暂停轮播
const carouselContainer = document.querySelector('.carousel-container');
if (carouselContainer) {
carouselContainer.addEventListener('mouseenter', stopSlideshow);
carouselContainer.addEventListener('mouseleave', startSlideshow);
}
// 当用户触摸屏幕时也暂停轮播
if (carouselContainer) {
carouselContainer.addEventListener('touchstart', stopSlideshow, {passive: true});
carouselContainer.addEventListener('touchend', startSlideshow, {passive: true});
}
// 添加触摸滑动支持
let touchStartX = 0;
let touchEndX = 0;
if (carouselContainer) {
carouselContainer.addEventListener('touchstart', (e) => {
touchStartX = e.changedTouches[0].screenX;
}, {passive: true});
carouselContainer.addEventListener('touchend', (e) => {
touchEndX = e.changedTouches[0].screenX;
handleSwipe();
}, {passive: true});
}
function handleSwipe() {
// 计算滑动距离
const swipeDistance = touchEndX - touchStartX;
const minSwipeDistance = 50; // 最小有效滑动距离
if (swipeDistance > minSwipeDistance) {
// 向右滑动,显示上一张
prevSlide();
} else if (swipeDistance < -minSwipeDistance) {
// 向左滑动,显示下一张
nextSlide();
}
startSlideshow();
}
// 启动轮播
startSlideshow();
});