用JS写一个手动轮播图
时间: 2023-04-06 14:05:13 浏览: 149
好的,我可以回答这个问题。以下是一个简单的手动轮播图的JS代码:
HTML代码:
```
<div class="slider">
<div class="slide">
<img src="image1.jpg">
</div>
<div class="slide">
<img src="image2.jpg">
</div>
<div class="slide">
<img src="image3.jpg">
</div>
</div>
<button class="prev">上一张</button>
<button class="next">下一张</button>
```
CSS代码:
```
.slider {
position: relative;
width: 600px;
height: 400px;
overflow: hidden;
}
.slide {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
.slide.active {
opacity: 1;
}
.prev,
.next {
position: absolute;
top: 50%;
transform: translateY(-50%);
background-color: #fff;
border: none;
padding: 10px;
cursor: pointer;
}
.prev {
left: 0;
}
.next {
right: 0;
}
```
JS代码:
```
const slides = document.querySelectorAll('.slide');
const prevBtn = document.querySelector('.prev');
const nextBtn = document.querySelector('.next');
let currentSlide = 0;
function showSlide(n) {
slides[currentSlide].classList.remove('active');
currentSlide = (n + slides.length) % slides.length;
slides[currentSlide].classList.add('active');
}
prevBtn.addEventListener('click', () => {
showSlide(currentSlide - 1);
});
nextBtn.addEventListener('click', () => {
showSlide(currentSlide + 1);
});
showSlide(currentSlide);
```
这个轮播图有三张图片,可以通过点击“上一张”和“下一张”按钮手动切换图片。
阅读全文