帮我用js写一个的轮播图的代码需要左右箭头以及小圆点进行切换并且还要定时切换
时间: 2024-05-07 07:17:40 浏览: 89
好的,以下是基于JavaScript实现的轮播图代码,其中包含左右箭头和小圆点进行切换,并且能够实现自动轮播功能:
HTML:
```
<div class="slider">
<div class="slider-wrapper">
<div class="slider-slide">Slider 1</div>
<div class="slider-slide">Slider 2</div>
<div class="slider-slide">Slider 3</div>
</div>
<a class="slider-prev"></a>
<a class="slider-next"></a>
<div class="slider-dots">
<span class="slider-dot active"></span>
<span class="slider-dot"></span>
<span class="slider-dot"></span>
</div>
</div>
```
CSS:
```
.slider {
position: relative;
overflow: hidden;
}
.slider-wrapper {
display: flex;
width: 300%; /* 3 Slides */
transition: transform 0.3s ease-in-out;
}
.slider-slide {
flex: 1;
text-align: center;
}
.slider-prev, .slider-next {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 40px;
height: 40px;
background-color: rgba(0, 0, 0, 0.5);
border-radius: 50%;
color: #fff;
text-align: center;
text-decoration: none;
font-size: 24px;
line-height: 40px;
opacity: 0.5;
transition: opacity 0.3s ease-in-out;
z-index: 1;
}
.slider-prev:hover, .slider-next:hover {
opacity: 1;
}
.slider-prev {
left: 10px;
}
.slider-next {
right: 10px;
}
.slider-dots {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
display: flex;
z-index: 1;
}
.slider-dot {
width: 10px;
height: 10px;
margin: 0 5px;
background-color: #fff;
border-radius: 50%;
cursor: pointer;
opacity: 0.5;
transition: opacity 0.3s ease-in-out;
}
.slider-dot.active {
opacity: 1;
}
```
JavaScript:
```
var slideIndex = 1;
var sliderWrapper = document.querySelector('.slider-wrapper');
var sliderSlides = document.querySelectorAll('.slider-slide');
var sliderPrev = document.querySelector('.slider-prev');
var sliderNext = document.querySelector('.slider-next');
var sliderDots = document.querySelectorAll('.slider-dot');
showSlide(slideIndex);
setInterval(function() {
slideIndex++;
showSlide(slideIndex);
}, 4000);
sliderPrev.addEventListener('click', function() {
slideIndex--;
showSlide(slideIndex);
});
sliderNext.addEventListener('click', function() {
slideIndex++;
showSlide(slideIndex);
});
for (var i = 0; i < sliderDots.length; i++) {
sliderDots[i].addEventListener('click', function() {
slideIndex = parseInt(this.dataset.slideIndex);
showSlide(slideIndex);
});
}
function showSlide(n) {
if (n > sliderSlides.length) {
slideIndex = 1;
}
if (n < 1) {
slideIndex = sliderSlides.length;
}
sliderWrapper.style.transform = 'translateX(' + (-(slideIndex - 1) * 100 / 3) +'%)';
for (var i = 0; i < sliderDots.length; i++) {
sliderDots[i].classList.remove('active');
}
sliderDots[slideIndex-1].classList.add('active');
}
```
希望能够帮到您!
阅读全文