函数调用的时候,传递四个必要的参数就行了。
参数1:要运动的ul;
参数2:左边按钮;
参数3:右边按钮;
参数4:运动速度;(可选,默认3s)
代码如下:
html部分:
<div class="div1">
<ul class="ul1">
<li>1111111111</li>
<li>2222222222</li>
<li>3333333333</li>
<li>4444444444</li>
<li>5555555555</li>
</ul>
</div>
<div>
<input id="btn1" type="button" value="←">
<input id="btn2" type="button" value="→">
</div>
css部分:
* { margin:0; padding:0;}
body { text-align:center;}
.div1 { overflow:hidden; width:350px; height:160px; margin:0 auto; border:3px solid #f00; position:relative;}
.ul1 { position:absolute; left:0; top:0;}
.ul1 li { width:100px; height:150px; float:left; list-style:none;}
js部分:
var imgScroll = {
//变量
oUl : null,
oLiWidth : 0,
oLiLength : 0,
btnLeft : null,
btnRight : null,
iIndex : 0,
timer : null,
speed : 0,
//函数
move : function(){
//复制ul里面的li
this.oUl.children('li').clone().appendTo(this.oUl);
this.oLiWidth = this.oUl.children('li').width();
this.oLiLength = this.oUl.children('li').length;
//设置ul宽度
this.oUl.width(this.oLiWidth*this.oLiLength);
var self = this;
//左边按钮
this.btnLeft.bind('click',function(){
clearInterval(self.timer);
if(self.iIndex==self.oLiLength/2){
self.iIndex = 0;
self.oUl.stop(true,true).css('left','0');
};
self.iIndex++;
self.oUl.stop(true,true).animate({left:-self.iIndex*self.oLiWidth},self.autoMove());
});
//右边按钮
this.btnRight.bind('click',function(){
clearInterval(self.timer);
if(self.iIndex==0){
self.iIndex = self.oLiLength/2;
self.oUl.stop(true,true).css('left',-self.iIndex*self.oLiWidth);
};
self.iIndex--;
self.oUl.stop(true,true).animate({left:-self.iIndex*self.oLiWidth},self.autoMove());
});
},
//自动轮播
autoMove : function(){
var self = this;
this.timer = setInterval(function(){
if(self.iIndex==self.oLiLength/2){
self.iIndex = 0;
self.oUl.stop(true,true).css('left','0');
};
self.iIndex++;
self.oUl.animate({left:-self.iIndex*self.oLiWidth});
},self.speed);
},
//初始化(运动的ul,左边按钮,右边按钮)
init : function(oUl, btnLeft, btnRight, speed){
this.oUl = oUl;
this.btnLeft = btnLeft;
this.btnRight = btnRight;
this.speed = speed ? speed*1000 : 3000;
this.move();
this.autoMove();
}
};
//调用
imgScroll.init($('.ul1'),$('#btn1'),$('#btn2'),2);
有不对或者可以优化的地方,请大家指正,谢谢!