HTML
<div id="carousel"> <div class="carousel-item"><img src="image1.jpg" alt=""></div> <div class="carousel-item"><img src="image2.jpg" alt=""></div> <div class="carousel-item"><img src="image3.jpg" alt=""></div> </div>
CSS
#carousel { width: 500px; height: 300px; position: relative; overflow: hidden; } .carousel-item { width: 100%; height: 100%; position: absolute; display: none; } .carousel-item img { width: 100%; height: 100%; }
JS
// 获取轮播图容器及轮播项 const carousel = document.getElementById('carousel'); const items = carousel.getElementsByClassName('carousel-item'); const totalItems = items.length; // 设置当前轮播项的索引 let currentIndex = 0; // 显示当前轮播项 function showItem(index) { // 隐藏所有轮播项 for (let i = 0; i < totalItems; i++) { items[i].style.display = 'none'; } // 显示指定索引的轮播项 items[index].style.display = 'block'; } // 切换到下一张轮播图 function nextItem() { currentIndex++; if (currentIndex >= totalItems) { currentIndex = 0; } showItem(currentIndex); } // 初始显示第一张轮播图 showItem(currentIndex); // 每隔3秒切换到下一张轮播图 setInterval(nextItem, 3000);