1.轮播图布局,图片,左右箭头切换,下标序号,实现样式布局方法有很多,这个仅供参考
<div class="box">
<ul class="img-wrapper">
<li class="img active">
<a href="">
<img src="./01.jpg" alt="">
</a>
</li>
<li class="img">
<a href="">
<img src="./02.jpg" alt="">
</a>
</li>
<li class="img">
<a href="">
<img src="./03.jpg" alt="">
</a>
</li>
<li class="img">
<a href="">
<img src="./04.jpg" alt="">
</a>
</li>
<li class="img">
<a href="">
<img src="./05.jpg" alt="">
</a>
</li>
</ul>
<ol class="btn">
<li class="active">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ol>
<div class="prev-row"></div>
<div class="next-row"></div>
2.其次就是样式设置,这个相对来说还是比较容易实现,这是一部分实现的样式设置,可以参考一下
.img-wrapper li {
list-style: none;
display: none;
}
.img-wrapper li.active {
display: block;
}
.btn {
display: flex;
list-style: none;
position: absolute;
right: 10px;
bottom: 10px;
}
.btn li {
width: 20px;
height: 20px;
border: 2px solid white;
border-radius: 50%;
text-align: center;
margin: 0 5px;
color: white;
font-size: 14px;
background-color: #333;
cursor: pointer;
}
3.接下来就是最重要的JS代码实现阶段,首先是下标序号点击切换图片,切换图片和按钮的选中状态是通过添加类名来实现选中状态的,这里要注意的是,要进行排他操作,先去掉所有图片选中状态,然后根据点击的索引去添加类名实现选中状态。
btnItems.forEach(function (btnItem, index) {
btnItem.onclick = function () {
//排他操作需要再遍历一次才能去除所有的active
btnItems.forEach(function (btnItem, btnIndex) {
//排他操作
currentIndex = index;
btnItem.classList.remove('active');
btnItems[currentIndex].classList.add('active');
imgItems[btnIndex].classList.remove('active');
imgItems[currentIndex].classList.add('active');
})
}
})
4.其次就是左右切换,这个是点击左箭头切换,需要进行一个判断就是索引的范围,不能小于0,所以如果索引小于0,就要把索引变成最大索引,右箭头点击切换代码大致是一样的,当前索引不是 --,改为 ++即可;
prev.onclick = function () {
currentIndex--;
currentIndex < 0 ? currentIndex = maxIndex : currentIndex;
btnItems.forEach(function (btnItem, index) {
btnItem.classList.remove('active');
btnItems[currentIndex].classList.add('active');
imgItems[index].classList.remove('active');
imgItems[currentIndex].classList.add('active');
})
}
5.最后一个便是自动播放了,创建定时器即可,里面切换图片和按钮的代码跟向右切换的代码基本一致,还有一个操作便是鼠标进入暂停,用mouseenter事件清除定时器,需要注意的是,清除定时器之后,需要再设置一个鼠标离开开启定时器,定时器内容一致
var intervalId = setInterval(function () {
currentIndex++;
currentIndex > maxIndex ? currentIndex = 0 : currentIndex;
btnItems.forEach(function (btnItem, index) {
btnItem.classList.remove('active');
btnItems[currentIndex].classList.add('active');
imgItems[index].classList.remove('active');
imgItems[currentIndex].classList.add('active');
})
}, 3000)
// 设置鼠标进入定时器关闭
box.onmouseenter = function () {
clearInterval(intervalId)
}
总的来说这个轮播图效果并不难,注意一些细节即可,这个是最初的版本,没有实现任何的切换效果,而且代码重复性太高,有很多相同的代码块其实是可以封装成函数就会简单很多,我的博客已上传完整代码,需要的可以去下载哦,后期我也会把其他效果和封装后的代码上传