以下是一个简单的 JavaScript 轮播图示例代码:
HTML:
<div class="slideshow-container"><div class="slide fade"><img src="img1.jpg"></div><div class="slide fade"><img src="img2.jpg"></div><div class="slide fade"><img src="img3.jpg"></div>
</div><button class="prev" onclick="plusSlides(-1)">❮</button>
<button class="next" onclick="plusSlides(1)">❯</button>
CSS:
.slideshow-container {position: relative;height: 400px;
}
.slideshow-container img {width: 100%;height: 400px;
}
.slide {position: absolute;width: 100%;height: 400px;display: none;
}
.prev, .next {position: absolute;top: 50%;transform: translateY(-50%);z-index: 1;padding: 10px;font-size: 30px;font-weight: bold;color: #fff;background-color: rgba(0,0,0,0.5);border: none;cursor: pointer;
}
.prev {left: 0;
}
.next {right: 0;
}
JavaScript:
var slideIndex = 1;
showSlides(slideIndex);function plusSlides(n) {showSlides(slideIndex += n);
}function showSlides(n) {var i;var slides = document.getElementsByClassName("slide");if (n > slides.length) {slideIndex = 1}if (n < 1) {slideIndex = slides.length}for (i = 0; i < slides.length; i++) {slides[i].style.display = "none";}slides[slideIndex-1].style.display = "block";
}
这个轮播图包含三个图片,分别是 img1.jpg
、img2.jpg
、img3.jpg
。CSS 中定义了轮播图容器 .slideshow-container
和图片样式,以及轮播图的按钮样式。JavaScript 中定义了轮播图的逻辑,包括 plusSlides()
和 showSlides()
两个函数,以及初始化轮播图的 showSlides(slideIndex)
函数。最后在 HTML 中定义了轮播图的容器和按钮。