原生JS实现轮播图的效果:
只要缕清了全局变量index的作用,这个轮播图也就比较容易实现了;另外,为了实现轮这个效果,有几处clearInterval()必须写上。废话不多说,直接上代码,修复了几个比较诡异的bug:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
body,ul,p{margin:0;padding:0;}
#boxs{position: relative;width:100%;height:460px;}
#box{width:100%;height:460px;}
ul{position:relative;width:100%;height:460px;}
li{width:100%;height:460px;position:absolute;}
img{width:100%;height:100%}
#circle{position: absolute;bottom:0;left:50%;transform: translate(-50%,0);}
#circle span{display:inline-block;height:20px;width:20px;background:white;vertical-align: top;border:1px solid yellow;border-radius:10px;/*float:left;*/}
.on{background:red !important;}
#left{position: absolute;background:red;height:80px;width:50px;line-height:80px;text-align: center;color:white;left:0;top:40%;}
#right{position: absolute;background:red;height:80px;width:50px;line-height:80px;text-align: center;color:white;right:0;top:40%;}
</style>
<script type="text/javascript">
window.onload=function(){
var circle_span=document.getElementById("circle").children;
var list=document.getElementById("ul1").children;
var box1=document.getElementById("boxs");
var btn1=document.getElementById("left");
var btn2=document.getElementById("right");
var timer=null;
var index=0;
play();
box1.onmouseover=function(){
clearInterval(timer);
}
box1.onmouseout=function(){
clearInterval(timer);
play();
}
btn1.onclick=function(){
index--;
if(index<0){
index=5;
}
change(index);
}
btn2.onclick=function(){
index++;
if(index>5){
index=0;
}
change(index);
}
for(var i=0;i<circle_span.length;i++){
circle_span[i].index=i;
circle_span[i].onmouseover=function(){
clearInterval(timer);
change(this.index);
index=this.index;
}
}
function play(){
timer=setInterval(function(){
index++;
if(index>5){
index=0;
}
change(index);
},1000);
}
function change(index){
for(var i=0;i<circle_span.length;i++){
circle_span[i].setAttribute("class","");
list[i].style.display="none";
}
circle_span[index].className="on";
list[index].style.display="block";
}
}
</script>
</head>
<body>
<div id="boxs">
<div id="box">
<ul id="ul1">
<li><img src="img/11.jpg"/></li>
<li><img src="img/22.jpg"/></li>
<li><img src="img/33.jpg"/></li>
<li><img src="img/44.jpg"/></li>
<li><img src="img/55.jpg"/></li>
<li><img src="img/66.jpg"/></li>
</ul>
</div>
<div id="circle">
<span class="on"></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
<div id="left">向左</div>
<div id="right">向右</div>
</div>
</body>
</html>