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;
430px;
height: 430px;
overflow: hidden;
}
#wrap {
position: absolute;
left: 0;
top: 0;
1720px;
height: 430px;
overflow: hidden;
}
#wrap img {
float: left;
}
#nav {
150px;
height: 30px;
list-style: none;
position: absolute;
bottom: 40px;
left: 0;
right: 0;
margin: auto;
}
#nav>li {
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="../images/imgA_2.jpg">
<img src="../images/imgB_2.jpg">
<img src="../images/imgC_2.jpg">
<img src="../images/imgD_2.jpg">
</div>
<ul id="nav">
<li class="selected"></li>
<li></li>
<li></li>
<li></li>
</ul>
</div> <script src="../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>
原文地址:https://www.cnblogs.com/xingxing88/p/6036459.html