js图片轮播和点击切换
时间: 2023-09-18 19:06:40 浏览: 83
js图片轮播
好的,下面是一个基本的JavaScript图片轮播和点击切换的实现方法:
HTML结构:
```
<div class="slider">
<img class="slide" src="image1.jpg">
<img class="slide" src="image2.jpg">
<img class="slide" src="image3.jpg">
<div class="prev"></div>
<div class="next"></div>
</div>
```
CSS样式:
```
.slider {
position: relative;
overflow: hidden;
}
.slide {
position: absolute;
top: 0;
left: 0;
opacity: 0;
transition: opacity 1s ease-in-out;
}
.slide.active {
opacity: 1;
}
.prev, .next {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 50px;
height: 50px;
background-color: rgba(0,0,0,0.5);
cursor: pointer;
}
.prev {
left: 0;
}
.next {
right: 0;
}
```
JavaScript代码:
```
var slides = document.querySelectorAll('.slide');
var currentSlide = 0;
var slideInterval = setInterval(nextSlide, 5000);
var prev = document.querySelector('.prev');
var next = document.querySelector('.next');
function nextSlide() {
slides[currentSlide].classList.remove('active');
currentSlide = (currentSlide + 1) % slides.length;
slides[currentSlide].classList.add('active');
}
function prevSlide() {
slides[currentSlide].classList.remove('active');
currentSlide = (currentSlide - 1 + slides.length) % slides.length;
slides[currentSlide].classList.add('active');
}
prev.addEventListener('click', prevSlide);
next.addEventListener('click', nextSlide);
```
上面的代码实现了自动轮播和点击切换的功能。其中,`slideInterval`变量是用来控制自动轮播的时间间隔的,可以根据需要进行调整。`prevSlide`和`nextSlide`函数分别实现了向前和向后切换的功能,其中使用了取模运算符来实现循环切换。最后,通过`addEventListener`方法来监听按钮的点击事件。
阅读全文