/** * 轮播图 */ document.addEventListener('DOMContentLoaded', function() { // 轮播图功能实现 const slides = document.querySelectorAll('.carousel-slide'); const prevButton = document.querySelector('.carousel-control.prev'); const nextButton = document.querySelector('.carousel-control.next'); const carouselContainer = document.querySelector('#banner-carousel'); let currentSlide = 0; let interval; // 检测是否为移动设备 const isMobile = window.matchMedia('(max-width: 768px)').matches; // 触摸事件变量 let touchStartX = 0; let touchEndX = 0; let touchStartY = 0; let touchEndY = 0; // 显示指定幻灯片 function showSlide(index) { // 隐藏所有幻灯片 slides.forEach(slide => { slide.style.opacity = 0; slide.style.zIndex = 0; }); // 显示当前幻灯片 slides[index].style.opacity = 1; slides[index].style.zIndex = 1; currentSlide = index; } // 下一张幻灯片 function nextSlide() { let next = currentSlide + 1; if (next >= slides.length) { next = 0; } showSlide(next); } // 上一张幻灯片 function prevSlide() { let prev = currentSlide - 1; if (prev < 0) { prev = slides.length - 1; } showSlide(prev); } // 自动轮播 function startAutoSlide() { interval = setInterval(nextSlide, 5000); // 5秒切换一次 } // 停止自动轮播 function stopAutoSlide() { clearInterval(interval); } // 显示控制按钮(仅桌面版) function showControls() { if (!isMobile) { prevButton.style.opacity = "1"; nextButton.style.opacity = "1"; } } // 隐藏控制按钮(仅桌面版) function hideControls() { if (!isMobile) { prevButton.style.opacity = "0"; nextButton.style.opacity = "0"; } } // 初始化显示第一张幻灯片 showSlide(0); // 开始自动轮播 startAutoSlide(); // 点击上一张按钮 prevButton.addEventListener('click', function(e) { e.stopPropagation(); // 防止事件冒泡 stopAutoSlide(); prevSlide(); startAutoSlide(); }); // 点击下一张按钮 nextButton.addEventListener('click', function(e) { e.stopPropagation(); // 防止事件冒泡 stopAutoSlide(); nextSlide(); startAutoSlide(); }); // 桌面端鼠标悬停事件 if (!isMobile) { // 鼠标悬停在轮播图上时停止自动轮播并显示控制按钮 carouselContainer.addEventListener('mouseenter', function() { stopAutoSlide(); showControls(); }); // 鼠标离开轮播图时恢复自动轮播并隐藏控制按钮 carouselContainer.addEventListener('mouseleave', function() { startAutoSlide(); hideControls(); }); } // 移动端触摸事件支持 carouselContainer.addEventListener('touchstart', function(e) { stopAutoSlide(); touchStartX = e.changedTouches[0].screenX; touchStartY = e.changedTouches[0].screenY; }, { passive: true }); carouselContainer.addEventListener('touchend', function(e) { touchEndX = e.changedTouches[0].screenX; touchEndY = e.changedTouches[0].screenY; handleSwipe(); startAutoSlide(); }, { passive: true }); // 处理滑动手势 function handleSwipe() { const xDiff = touchEndX - touchStartX; const yDiff = touchEndY - touchStartY; // 确保是水平滑动而不是垂直滚动 if (Math.abs(xDiff) > Math.abs(yDiff) && Math.abs(xDiff) > 50) { if (xDiff > 0) { // 右滑 - 上一张 prevSlide(); } else { // 左滑 - 下一张 nextSlide(); } } } });