首页 > 代码库 > JQUERY实现轮播

JQUERY实现轮播

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>轮播</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#container {
position: relative;
left: 0;
top: 0;
width: 430px;
height: 430px;
overflow: hidden;
}
#wrap {
position: absolute;
left: 0;
top: 0;
width: 1720px;
height: 430px;
overflow: hidden;
}
#wrap img {
float: left;
}
#nav {
width: 150px;
height: 30px;
list-style: none;
position: absolute;
bottom: 40px;
left: 0;
right: 0;
margin: auto;
}
#nav>li {
width: 30px;
height: 30px;
border-radius: 30px;
background-color: rgba(255, 255, 255, 0.6);
float: left;
margin-left: 10px;
cursor: pointer;
}
#nav>li:first-child {
margin-left: 0;
}
#nav .selected{
background-color: #60b000;
}
</style>
</head>
<body>
<div id="container">
<div id="wrap">
<img src=http://www.mamicode.com/"../images/imgA_2.jpg">
<img src=http://www.mamicode.com/"../images/imgB_2.jpg">
<img src=http://www.mamicode.com/"../images/imgC_2.jpg">
<img src=http://www.mamicode.com/"../images/imgD_2.jpg">
</div>
<ul id="nav">
<li class="selected"></li>
<li></li>
<li></li>
<li></li>
</ul>
</div> <script src="http://www.mamicode.com/js/jquery-1.12.4.js"></script>
<script >
$(function(){
$(‘#wrap‘).data(‘index‘,0);
$(‘#nav‘).on(‘click‘,‘li‘,function(){
//清除自动播放的定时器
clearInterval(timer);

var index=$(this).index();
var that=this;
//把当前要显示的索引号,保存到附加数据中
$(‘#wrap‘).data(‘index‘,index).animate({
left:index*(-430)
},1000,function(){
$(‘#nav li‘).removeClass(‘selected‘);
$(that).addClass(‘selected‘);
//重启自动播放的定时器
timer=setInterval(autoPlay,2000);
});

});

var timer=setInterval(autoPlay,2000);
//自动播放功能
function autoPlay(){
//获取当前的索引号
var currentIndex=$(‘#wrap‘).data(‘index‘);
//下一个索引号
var nextIndex;
if(currentIndex===$(‘#wrap img‘).length-1){
nextIndex=0;
}else{
nextIndex=currentIndex+1;
}
$(‘#wrap‘).data(‘index‘,nextIndex).animate({
left:nextIndex*(-430)
},1000,function(){
$(‘#nav li‘).removeClass(‘selected‘).eq(nextIndex).addClass(‘selected‘);
});
}

});
</script>
</body></html>

JQUERY实现轮播