jquery实现轮播图

根据昨天写的换肤写到的一部分的图片轮播,今天把它完善一下。先看看最后的效果图:

jquery实现轮播图

jquery实现轮播图

下面是源码:

//简单的布局

<body>
<div id="content">
<div class="img">
<img src="img/1.jpg" height="200" width="600" alt="">
<img src="img/2.jpg" height="200" width="600" alt="">
<img src="img/3.jpg" height="200" width="600" alt="">
<img src="img/4.jpg" height="200" width="600" alt="">
<img src="img/5.jpg" height="200" width="600" alt="">
<img src="img/2.jpg" height="200" width="600" alt="">
<img src="img/3.jpg" height="200" width="600" alt="">
</div>
<ul id="ul1">
<li class="active">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
</ul>
</div>

</body>

//样式

<style>
*{ margin:0;padding:0; }
#content{ width: 600px;height: 200px;margin:100px auto 0; position: relative;overflow: hidden;}
#content .img{ width: 600px;height: 1000px; position: absolute;top:0;left:0;}
#content .img img{ display: block; }/*加上后图片之间没有间隙*/
#ul1{ width: 200px;height: 20px;position: absolute;bottom:3px; right:0;}
#ul1 li{ list-style: none;width: 20px;height: 20px;line-height:20px;float:left;background: #605c5d;margin-right: 5px;text-align: center;font-size: 12px;border-radius: 50%;color:#f1f1f1;
text-shadow:1px 1px #9f9496;}
#ul1 .active{ background: #f0475a; }

</style>

//接着是Jquery

<script src="js/jquery-1.11.0.min.js"></script>
<script>
$(function(){
var _index=0;
var timer=null;
$('#ul1 li').hover(function(){
clearInterval(timer);//当鼠标移入时,先把定时器清空
_index=$(this).index();
$(this).addClass('active').siblings().removeClass('active');
$('.img').animate({top:-(_index*200)},1000);
},function(){
autoplay();//鼠标移出后,再次执行自动播放函数
});
//自动轮播
function autoplay(){
//定义一个定时器,每隔2秒自动换下一张
timer=setInterval(function(){
_index++;
if(_index>6){
_index=0;//跳到最后一张时,又回到第一张
}
$('#ul1 li').eq(_index).addClass('active').siblings().removeClass('active');
$('.img').animate({top:-(_index*200)},1000);

},2000);

}
autoplay();
});

</script>

简单总结:主要是改变包裹图片的div的top值。实现数字索引与图片一致时,需要定义一个_index索引号。实现图片自动轮播时,用到定时器,由于有鼠标事件,又有定时器,如果在进行鼠标事件时,不清楚定时器,会造成混乱,因此每次进行鼠标事件时,需要清楚定时器,当不进行鼠标事件时,又要把定时器开启。