JavaScript之轮播图

独自空忆成欢 提交于 2019-12-22 05:20:04

(1)html

<div class="box" id="box">
<ul class="uls" id="uls">
<li><img src="img/one.jpg" alt=""></li>
<li><img src="img/two.jpg" alt=""></li>
<li><img src="img/three.jpg" alt=""></li>
<li><img src="img/four.jpg" alt=""></li>
<li><img src="img/five.jpg" alt=""></li>
<li><img src="img/six.jpg" alt=""></li>
</ul>

<span id="left">左</span>
<span id="right">右</span>
<ol id="ols" class="ols">
<li class="selected"></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ol>
</div>

(2)css

*{
margin: 0px;
padding: 0px;
}
.box{
width: 520px;
height: 280px;
border: 1px solid #000;
margin: 50px auto;
overflow: hidden;
position: relative;
}
.uls{
list-style: none;
width: 99999px;
/*给ul足够大的宽度,使li可以全部水平排列*/
}
.uls li{
float: left;
}

.box>span{
position: absolute;
width: 20px;
height: 30px;
background: rgba(0,0,0,0.7);
top: 50%;
margin-top: -15px;
color: white;
cursor: pointer;
text-align: center;
line-height: 30px;
}
#left{
left: 20px;
}
#right{
right: 20px;
}

.ols{
position: absolute;
bottom: 20px;
left: 50%;
margin-left: -111px;
list-style: none;
}
.ols li{
float: left;
width: 20px;
height: 20px;
border-radius: 50%;
border: 1px solid #f60;
margin-right: 15px;
cursor: pointer;
}
.ols li.selected{
background: #f60;
}

(3)JavaScript

var ouls=document.getElementById('uls');
var obox=document.getElementById('box');
var oright=document.getElementById('right');
var oleft=document.getElementById('left');
var olis=document.getElementById('ols').children;
var timer;
var num=0;

function go(){
// 自动轮播
timer=setInterval(function(){
num++;
if(num>5){
num=0;
}
ouls.style.marginLeft=-520*num+'px';

for(var i=0;i<olis.length;i++){
olis[i].setAttribute('class','');
}
olis[num].setAttribute('class','selected');
},1000)
}
go();

obox.onmouseenter=function(){
// 鼠标移入,停止定时器
clearInterval(timer);
}

obox.onmouseleave=function(){
// 鼠标移出,启动定时器
go();
}

// 点击向右按钮
oright.onclick=function(){
num++;
if(num>5){
num=0;
}
ouls.style.marginLeft=-520*num+'px';

for(var i=0;i<olis.length;i++){
olis[i].setAttribute('class','');
}
olis[num].setAttribute('class','selected');
}
// 点击向左按钮
oleft.onclick=function(){
num--;
if(num<0){
num=5;
}
ouls.style.marginLeft=-520*num+'px';

for(var i=0;i<olis.length;i++){
olis[i].setAttribute('class','');
}
olis[num].setAttribute('class','selected');
}

// 底部导航栏
for(var i=0;i<olis.length;i++){
olis[i].setAttribute('index', i);
olis[i].onclick=function(){
num=this.getAttribute('index');
for(var i=0;i<olis.length;i++){
olis[i].setAttribute('class','');
}
this.setAttribute('class', 'selected');

ouls.style.marginLeft=-520*num+'px';

}
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!