carousel.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. function initCarousel(rootEl) {
  2. const carousel = rootEl.querySelector('.carousel');
  3. const carouselInner = carousel.querySelector('.carousel-inner');
  4. const carouselItems = carousel.querySelectorAll('.carousel-item');
  5. const prevBtn = carousel.querySelector('.prev');
  6. const nextBtn = carousel.querySelector('.next');
  7. const indicators = carousel.querySelectorAll('.indicator');
  8. let currentIndex = 0;
  9. const itemWidth = 100; // 百分比
  10. const totalItems = carouselItems.length;
  11. // 更新轮播显示
  12. function updateCarousel() {
  13. carouselInner.style.transform = `translateX(-${currentIndex * itemWidth}%)`;
  14. // 更新指示器状态
  15. indicators.forEach((indicator, index) => {
  16. if (index === currentIndex) {
  17. indicator.classList.add('active');
  18. } else {
  19. indicator.classList.remove('active');
  20. }
  21. });
  22. }
  23. // 上一张
  24. prevBtn.addEventListener('click', function() {
  25. currentIndex = (currentIndex - 1 + totalItems) % totalItems;
  26. updateCarousel();
  27. });
  28. // 下一张
  29. nextBtn.addEventListener('click', function() {
  30. currentIndex = (currentIndex + 1) % totalItems;
  31. updateCarousel();
  32. });
  33. // 点击指示器切换
  34. indicators.forEach(indicator => {
  35. indicator.addEventListener('click', function() {
  36. currentIndex = parseInt(this.getAttribute('data-index'));
  37. updateCarousel();
  38. });
  39. });
  40. // 自动轮播
  41. let autoplayInterval = setInterval(function() {
  42. currentIndex = (currentIndex + 1) % totalItems;
  43. updateCarousel();
  44. }, 5000);
  45. // 鼠标悬停暂停自动轮播
  46. carousel.addEventListener('mouseenter', function() {
  47. clearInterval(autoplayInterval);
  48. });
  49. // 鼠标离开恢复自动轮播
  50. carousel.addEventListener('mouseleave', function() {
  51. autoplayInterval = setInterval(function() {
  52. currentIndex = (currentIndex + 1) % totalItems;
  53. updateCarousel();
  54. }, 5000);
  55. });
  56. }