轮播图是网站设计常用的一种功能,请看代码。
css样式:
.wraper{
width: 300px;
height: 200px;
position: relative;
}
.wraper>img{
display: none;
width: 300px;
height: 200px;
}
#pre{
width: 30px;
height: 50px;
background-color: rgba(100,100,100,0.8);
color: #ffffff;
position: absolute;
left: 0;
top: calc(50% - 25px);
text-align: center;
line-height: 50px;
}
#next{
width: 30px;
height: 50px;
background-color: rgba(100,100,100,0.8);
color: #ffffff;
position: absolute;
right: 0;
top: calc(50% - 25px);
text-align: center;
line-height: 50px;
}
.wraper>.active{
display: block;
}
.circle{
position: absolute;
bottom: 20px;
left: calc(50% - 60px);
}
span{
width: 30px;
height: 30px;
display: inline-block;
border-radius: 50%;
background-color: rgba(100,100,100,0.8);
}
.active_circle{
background-color: #ccc;
}
html部分:
<img src="../img/img/1.jpg" class="active" alt="">
<img src="../img/img/2.jpg" alt="">
<img src="../img/img/3.jpg" alt="">
<img src="../img/img/4.jpg" alt="">
<div id="pre"> < </div>
<div id="next"> > </div>
<div class="circle">
<span class="active_circle"></span>
<span></span>
<span></span>
<span></span>
js部分:
var spans = document.getElementsByTagName('span')
var pre = document.getElementById('pre')
var next = document.getElementById('next')
// var imgs=document.querySelectorAll('.wraper>img')
var imgs = document.getElementsByTagName('img')
//声明计数器显示有图片索引值
var count = 0
next.onclick = function () {
++count
for (var i = 0; i < imgs.length; i++) {
imgs[i].className = ''
spans[i].className = ''
}
if (count >= 4) {
count = 0
}
imgs[count].className = 'active'
spans[count].className = 'active_circle'
}
pre.onclick = function () {
--count
for (var i = 0; i < imgs.length; i++) {
imgs[i].className = ''
spans[i].className = ''
}
if (count < 0) {
count = 3
}
imgs[count].className = 'active'
spans[count].className = 'active_circle'
}
//给小求添加属性i 为span索引值
for (var i = 0; i < spans.length; i++) {
spans[i].i = i //记录用户点击哪个小圆点
spans[i].onclick = function () {
//清空样式
for (var j = 0; j < spans.length; j++) {
spans[j].className = ''
imgs[j].className = ''
}
var index = this.i //保存当前点击源点索引值
count = index //保证上一个下一个,以当前元素为基础进行count++ --
this.className = 'active_circle'
imgs[index].className = 'active'
}
}