左右键操作轮播图 以及小圆点切换轮播图
时间: 2023-07-18 21:36:25 浏览: 142
轮播图切换
5星 · 资源好评率100%
好的,关于左右键操作轮播图和小圆点切换轮播图的实现方法,可以参考以下代码:
HTML代码:
```
<div class="slider">
<ul class="slides">
<li><img src="img/slide1.jpg"></li>
<li><img src="img/slide2.jpg"></li>
<li><img src="img/slide3.jpg"></li>
</ul>
<a class="prev" onclick="prevSlide()">❮</a>
<a class="next" onclick="nextSlide()">❯</a>
<div class="dots">
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
</div>
</div>
```
CSS代码:
```
.slider {
width: 600px;
height: 400px;
position: relative;
overflow: hidden;
}
.slides {
width: 1800px;
height: 400px;
padding: 0;
margin: 0;
list-style: none;
position: absolute;
top: 0;
left: 0;
}
.slides li {
float: left;
width: 600px;
height: 400px;
}
.prev, .next {
position: absolute;
top: 50%;
transform: translateY(-50%);
font-size: 30px;
display: block;
cursor: pointer;
z-index: 1;
}
.prev {
left: 10px;
}
.next {
right: 10px;
}
.dots {
text-align: center;
margin-top: 10px;
}
.dot {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #bbb;
margin: 0 5px;
cursor: pointer;
}
.active {
background-color: #717171;
}
```
JavaScript代码:
```
var slides = document.querySelector('.slides');
var slideIndex = 1;
var dots = document.querySelectorAll('.dot');
function showSlide(n) {
var slidesList = slides.querySelectorAll('li');
if (n > slidesList.length) {
slideIndex = 1;
}
if (n < 1) {
slideIndex = slidesList.length;
}
for (var i = 0; i < slidesList.length; i++) {
slidesList[i].style.display = 'none';
}
slidesList[slideIndex - 1].style.display = 'block';
for (var j = 0; j < dots.length; j++) {
dots[j].classList.remove('active');
}
dots[slideIndex - 1].classList.add('active');
}
function prevSlide() {
showSlide(slideIndex -= 1);
}
function nextSlide() {
showSlide(slideIndex += 1);
}
function currentSlide(n) {
showSlide(slideIndex = n);
}
showSlide(slideIndex);
setInterval(function() {
nextSlide();
}, 3000);
```
这个代码同时实现了左右键切换轮播图和小圆点切换轮播图,左右键通过onClick事件触发prevSlide()和nextSlide()函数,小圆点通过onClick事件触发currentSlide()函数。每隔3秒钟自动切换图片。
阅读全文