用Jquery 实现轮播效果
该轮播主要实现以下几个效果
- 从左向右自动播放
- 在轮播的左右有按钮,可以让图片向左或者向右
- 点击滑动按钮一定时间后继续自动播放
- 避免鼠标连点触发时间
首先附上html 代码:
<div class="sliderImg">
<div id="banner">
<ul>
<li><img src="img/life1.jpg"></li>
<li><img src="img/life2.jpg"></li>
<li><img src="img/life3.jpg"></li>
<li><img src="img/life4.jpg"></li>
<li><img src="img/life5.jpg"></li>
</ul>
<div class="butt">
<a id="buttleft"><</a>
<a id="buttright">></a>
</div>
<span style="position:absolute ;left:500px;bottom:100px;background-color: white;opacity: 0.6 ;font-size:20px ">————记录你的朝阳,记录的岁月春秋
</span>
</div>
</div>
里面有两个按钮,5张图片,还有一个标语框。按钮绝对定位在左右两侧,标语框定位在右下方。
以下是CSS代码:
.sliderImg ul li{
float:left;
width:800px;
height:450px;
list-style: none;
position:relative;
overflow:hidden;
display: inline;
}
.sliderImg ul li img{
width:800px;
height: 450px;
position:absolute;
}
.sliderImg ul{
width:4000px;
height:450px;
padding:0;
}
.sliderImg{
margin:0 auto;
width:800px;
height:450px;
overflow:hidden;
clear:both;
}
.butt{
postion:relative;
}
#buttleft{
position:absolute;
bottom:175px;
left:50px;
font-size: 60px;
color:white;
opacity: 0.7;
}
#buttright {
position: absolute;
bottom: 175px;
right: 10px;
font-size: 60px;
color: white;
opacity: 0.7;
}
#banner{
position:relative;
width: 800px;
height: 450px;
overflow: hidden;
}
将整个ul的长度设置为所有的图片的宽度总和,所有的li向左浮动,但是在外部的div宽度只设置为一张图片的长度,这样就只显示一张图片。
下面是js代码:
var loopSliderImg=(function(){
var $butleft=null;
var $butright=null;
var curIndex=0;
var $imgList=null;
var imgLen=null;
var autochange=null;
var animateFlag=false;
function init(){
$butleft=$("#buttleft");
$butright=$("#buttright");
imgLen=$("#banner ul li ").length;
$imgList=$("#banner ul li");
setEvent();//设置左右按钮的事件
autoPlayer();//自动播放函数
}
function setEvent(){
$butleft.on("click",function(){
anigo(-1);
});
$butright.on("click",function(){
anigo(1);
});
}
function anigo(d){
if(animateFlag)//判断动画是否在进行
{
return false;
}
animateFlag=true;
clearInterval(autochange);
if(d<0)
{
curIndex=(curIndex > 0) ? (--curIndex) : (imgLen - 1);
}
if(d>0)
{
curIndex = (curIndex < imgLen - 1) ? (++curIndex) : 0;
}
changeTo(curIndex);
animateFlag=false;//判断动画已经做完
setTimeout(function(){
clearInterval(autochange);
autoPlayer();
},2500);
}
function autoPlayer(){
autochange=setInterval(function() {
if(curIndex < (imgLen-1)){
curIndex++;
}
else{
curIndex=0;
}
changeTo(curIndex);
},2500);
}
function changeTo(num){
var autoGoLetf=num*800;
$imgList.animate({left:"-"+autoGoLetf+"px"},500);
}
return init;
})();
loopSliderImg();
这个功能主要依靠的是图片left属性的改变,即每次将图片向左或右移动一张图片的距离,并且设置0.5秒的动画事件。并且在点击按钮的函数中,添加一个标记位来确定动画是否已经进行完毕。