?HTML結構:
創建一個輪播圖的容器,并在其中放置輪播圖片。
<div id="carousel"> <div class="carousel-item active"> <img src="image1.jpg" alt="Image 1"> </div> <div class="carousel-item"> <img src="image2.jpg" alt="Image 2"> </div> <!-- 更多圖片... -->
</div> <button id="prevBtn">上一張</button>
<button id="nextBtn">下一張</button>
-
CSS樣式:為輪播圖和按鈕添加樣式。
#carousel { position: relative; overflow: hidden; width: 100%; height: 0; padding-bottom: 56.25%; /* 16:9 Aspect Ratio */
} .carousel-item { position: absolute; top: 0; left: 100%; width: 100%; height: 100%; transition: left 0.5s ease-in-out;
} .carousel-item img { width: 100%; height: 100%; object-fit: cover;
} .carousel-item.active { left: 0;
} #prevBtn, #nextBtn { position: absolute; top: 50%; transform: translateY(-50%); background-color: rgba(0, 0, 0, 0.5); color: white; border: none; padding: 10px; cursor: pointer;
} #prevBtn { left: 10px;
} #nextBtn { right: 10px;
}
?JavaScript邏輯:
使用JavaScript來控制輪播圖的切換
?
// 模擬接口返回的圖片數量
const imageCount = 5; // 獲取DOM元素
const carousel = document.getElementById('carousel');
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn'); // 創建輪播圖項
for (let i = 0; i < imageCount; i++) { const item = document.createElement('div'); item.classList.add('carousel-item'); const img = document.createElement('img'); img.src = `image${i + 1}.jpg`; img.alt = `Image ${i + 1}`; item.appendChild(img); carousel.appendChild(item);
} // 設置初始激活狀態
carousel.querySelector('.carousel-item').classList.add('active'); // 上一張/下一張圖片
let currentIndex = 0;
prevBtn.addEventListener('click', () => { currentIndex--; if (currentIndex < 0) currentIndex = imageCount - 1; updateCarousel();
}); nextBtn.addEventListener('click', () => { currentIndex++; if (currentIndex >= imageCount) currentIndex = 0; updateCarousel();
}); // 更新輪播圖
function updateCarousel() { const items = carousel.querySelectorAll('.carousel-item'); items.forEach(item => item.classList.remove('active')); items[currentIndex].classList.add('active');
}
?