四张图片每隔2秒换下一张
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
*{padding: 0;margin: 0;}
body{background-color: green;}
#cou{width: 540px;height: 400px;margin: 30px auto;position: relative;}
#content img{width: 540px;height: 400px;}
#content div{display: none;}
#content div.on{display: block;}
ol,li{list-style: none;}
ol{position: absolute;bottom: 15px;left: 50%;transform: translateX(-50%);}
.item li{float: left;width: 10px;height: 10px;border-radius: 50%;background-color: #fff;
margin-right: 10px;}
.item li.current{background-color: orange;}
.arrow{width: 32px;height: 32px;display: inline-block;position: absolute;
top: 184px;background: rgba(255,255,255,0.3);display: none;}
.arrow img{width: 28px;height: 28px;margin-top: 2px;}
.ar{right: 0px;transform: rotateY(180deg);}
</style>
</head>
<body>
<!-- 轮播图 -->
<div id="cou">
<!-- 轮播区 -->
<div id="content">
<div class="on"><img src="./images/1.jpg" alt=""></div>
<div><img src="./images/2.jpg" alt=""></div>
<div><img src="./images/3.jpg" alt=""></div>
<div><img src="./images/4.jpg" alt=""></div>
</div>
<ol class="item">
<li class="current"></li>
<li></li>
<li></li>
<li></li>
</ol>
<a href="#" class="arrow al"><img src="./images/arrow.png" alt=""></a>
<a href="#" class="arrow ar"><img src="./images/arrow.png" alt=""></a>
</div>
<script type="text/javascript">
//获取元素
var o=document.querySelector('#cou');
var ds=document.querySelector('#content').querySelectorAll('div');
var lis=document.querySelector('.item').querySelectorAll('li');
var arrows=document.querySelectorAll('.arrow');
var index=0;//保存当前展示的轮播图的索引 ,默认0
var len=ds.length;
var t;
//1.自动轮播
t=setInterval(moveNext,2000);
//鼠标经过,停止轮播
o.function(){
clearInterval(t);
o.style.cursor='pointer';
arrows[0].style.display='block';
arrows[1].style.display='block';
};
//鼠标离开,继续轮播
o.function(){
t=setInterval(moveNext,2000);
arrows[0].style.display='none';
arrows[1].style.display='none';
};
//2.指示器轮播
for(var i=0;i<len;i++){
lis[i]._index=i;//新增属性,保存位置
//为每一个li追加点击事件
lis[i].function(){
//当前显示的li,修改为未选中状态
lis[index].className='';
ds[index].className='';//当前显示的轮播图改为不显示
this.className='current';//被点击的li,改为选中状态
ds[this._index].className='on';//轮播显示为对应
//修改index值
index=this._index;
};
}
//3.箭头轮播
//右箭头
arrows[1].function(){
moveNext();
};
//左箭头
arrows[0].function(){
movePre();
};
//切换下一张
function moveNext() {
ds[index].className='';//当前显示的轮播图改为不显示
lis[index].className='';//当前指示器不显示
index++;//索引递增
if(index==len){
index=0;//最后一张,切换为第一张
}
ds[index].className='on';//下一张显示
lis[index].className='current';
}
//上一张
function movePre(){
//当前显示的---->不显示
ds[index].className='';
lis[index].className='';
index--;
if(index==-1){
index=len-1;//第一张时,修改为最后一站
}
//上一张展示
ds[index].className='on';
lis[index].className='current';
}
</script>
</body>
</html>