1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- function initCarousel(rootEl) {
- const carousel = rootEl.querySelector('.carousel');
- const carouselInner = carousel.querySelector('.carousel-inner');
- const carouselItems = carousel.querySelectorAll('.carousel-item');
- const prevBtn = carousel.querySelector('.prev');
- const nextBtn = carousel.querySelector('.next');
- const indicators = carousel.querySelectorAll('.indicator');
- let currentIndex = 0;
- const itemWidth = 100; // 百分比
- const totalItems = carouselItems.length;
- // 更新轮播显示
- function updateCarousel() {
- carouselInner.style.transform = `translateX(-${currentIndex * itemWidth}%)`;
-
- // 更新指示器状态
- indicators.forEach((indicator, index) => {
- if (index === currentIndex) {
- indicator.classList.add('active');
- } else {
- indicator.classList.remove('active');
- }
- });
- }
- // 上一张
- prevBtn.addEventListener('click', function() {
- currentIndex = (currentIndex - 1 + totalItems) % totalItems;
- updateCarousel();
- });
- // 下一张
- nextBtn.addEventListener('click', function() {
- currentIndex = (currentIndex + 1) % totalItems;
- updateCarousel();
- });
- // 点击指示器切换
- indicators.forEach(indicator => {
- indicator.addEventListener('click', function() {
- currentIndex = parseInt(this.getAttribute('data-index'));
- updateCarousel();
- });
- });
- // 自动轮播
- let autoplayInterval = setInterval(function() {
- currentIndex = (currentIndex + 1) % totalItems;
- updateCarousel();
- }, 5000);
- // 鼠标悬停暂停自动轮播
- carousel.addEventListener('mouseenter', function() {
- clearInterval(autoplayInterval);
- });
- // 鼠标离开恢复自动轮播
- carousel.addEventListener('mouseleave', function() {
- autoplayInterval = setInterval(function() {
- currentIndex = (currentIndex + 1) % totalItems;
- updateCarousel();
- }, 5000);
- });
- }
|