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'); }