JavaScript 实现轮播效果主要依赖于定时器(如 setInterval
)和 DOM 操作。以下是一个简单的轮播效果实现示例:
setInterval
函数可以周期性地执行某段代码。<div id="carousel">
<img src="image1.jpg" alt="Image 1" class="active">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
#carousel {
width: 100%;
overflow: hidden;
position: relative;
}
#carousel img {
width: 100%;
height: auto;
position: absolute;
opacity: 0;
transition: opacity 1s ease-in-out;
}
#carousel img.active {
opacity: 1;
}
const carouselImages = document.querySelectorAll('#carousel img');
let currentIndex = 0;
function showNextImage() {
// Hide current image
carouselImages[currentIndex].classList.remove('active');
// Move to next image
currentIndex = (currentIndex + 1) % carouselImages.length;
// Show next image
carouselImages[currentIndex].classList.add('active');
}
// Set interval to change image every 3 seconds
setInterval(showNextImage, 3000);
通过以上步骤和代码示例,你可以实现一个基本的轮播效果。根据具体需求,还可以进一步扩展功能,如添加导航按钮、指示器等。
领取专属 10元无门槛券
手把手带您无忧上云