JavaScript轮播图
以下是一个简单的JavaScript轮播图实现的示例代码:
HTML部分:
<div class="carousel">
<div class="carousel-inner">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
<!-- 更多图片... -->
</div>
<button class="prev">Previous</button>
<button class="next">Next</button>
</div>
CSS部分:
.carousel-inner img {
display: none;
width: 100%;
}
.carousel-inner img.active {
display: block;
}
JavaScript部分:
document.addEventListener('DOMContentLoaded', function() {
var currentIndex = 0;
var images = document.querySelectorAll('.carousel-inner img');
var prevButton = document.querySelector('.prev');
var nextButton = document.querySelector('.next');
function showImage(index) {
images.forEach(img => img.classList.remove('active'));
images[index].classList.add('active');
}
function nextImage() {
currentIndex = (currentIndex + 1) % images.length;
showImage(currentIndex);
}
function prevImage() {
currentIndex = (currentIndex - 1 + images.length) % images.length;
showImage(currentIndex);
}
showImage(currentIndex);
nextButton.addEventListener('click', nextImage);
prevButton.addEventListener('click', prevImage);
});
这段代码实现了一个基本的轮播图功能,通过点击按钮切换图片。currentIndex
变量用于跟踪当前激活的图片。showImage
函数用于切换图片的显示状态,nextImage
和prevImage
分别用于处理下一张和上一张图片的逻辑。
评论已关闭