用前端写一个简易的手动轮播图
时间: 2023-09-17 17:07:24 浏览: 140
很简单很基础的前端轮播图
好的,以下是一个简单的手动轮播图的前端实现,使用 HTML、CSS 和 JavaScript:
HTML:
```
<div class="carousel">
<div class="carousel-slide">
<img src="image1.jpg">
</div>
<div class="carousel-slide">
<img src="image2.jpg">
</div>
<div class="carousel-slide">
<img src="image3.jpg">
</div>
<div class="carousel-slide">
<img src="image4.jpg">
</div>
<a class="carousel-prev" href="#">❮</a>
<a class="carousel-next" href="#">❯</a>
</div>
```
CSS:
```
.carousel {
position: relative;
width: 100%;
overflow: hidden;
}
.carousel-slide {
float: left;
width: 100%;
position: relative;
}
.carousel-slide img {
width: 100%;
}
.carousel-prev,
.carousel-next {
position: absolute;
top: 50%;
transform: translateY(-50%);
font-size: 30px;
color: white;
text-decoration: none;
z-index: 1;
}
.carousel-prev {
left: 0;
}
.carousel-next {
right: 0;
}
```
JavaScript:
```
var slideIndex = 1;
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("carousel-slide");
var dots = document.getElementsByClassName("dot");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
}
var prev = document.querySelector('.carousel-prev');
var next = document.querySelector('.carousel-next');
prev.addEventListener('click', function() {
plusSlides(-1);
});
next.addEventListener('click', function() {
plusSlides(1);
});
```
这个轮播图支持手动切换图片,点击 `.carousel-prev` 向前切换图片,点击 `.carousel-next` 向后切换图片。你可以通过修改 CSS 来改变轮播图的样式,例如添加动画效果、调整大小等。
阅读全文