用jq實現無限輪播
阿新 • • 發佈:2019-01-27
$(function(){
function Slide(){
this.data={
img_width:300,
img_height:300,
btn_width:40,
btn_height:40,
num:4,
delay:300
};
var self=this
this.index=1;
this.timer=null;
this.wrapper=$('.wrapper');
this.wrapperContent=$('.wrapper-content');
this.wrapperContentImg=$('.wrapper-content_img');
this.wrapperButton=$('.wrapper-button');
this .wrapperButtons=$('.wrapper-buttons')
this.wrapperPrev=$('.wrapper-prev');
this.wrapperNext=$('.wrapper-next');
this.setCss()
this.wrapper.hover(function(){
self.stop()
},
function(){
self.play()
})
this .play()
this.wrapperPrev.bind('click',function(){
self.prev()
})
this.wrapperNext.bind('click',function(){
self.next()
})
this.wrapperButton.each(function(){
var _this=self
$(this).bind('click',function(){
if (_this.wrapperContent.is(':animated') || $(this).attr('class')=='on') {
return;
}
var offset=($(this).attr('index')-_this.index)*_this.data.img_width;
_this.index=$(this).attr('index')
_this.animate(offset)
_this.showButton()
})
})
}
Slide.prototype={
setCss:function(){
var self=this;
this.wrapper.css({
width:self.data.img_width,
height:self.data.img_height,
})
this.wrapperContent.css({
left:-self.data.img_width,
width:self.data.img_width*(self.data.num+2),
height:self.data.img_height,
})
this.wrapperPrev.css({
marginTop:-parseInt(self.data.btn_height/2)
})
this.wrapperNext.css({
marginTop:-parseInt(self.data.btn_height/2)
})
this.wrapperContentImg.css({
width:self.data.img_width,
height:self.data.img_height
})
this.wrapperButtons.css({
left:(self.data.img_width-100)/2
})
},
next:function(){
if(this.wrapperContent.is(':animated')){
return
}
if(this.index==this.data.num){
this.index=1
}else{
this.index+=1
}
this.animate(this.data.img_width)
this.showButton()
},
prev:function(){
if(this.wrapperContent.is(':animated')){
return
}
if(this.index==1){
this.index=this.data.num
}else{
this.index-=1
}
this.animate(-this.data.img_width)
this.showButton()
},
animate:function(offset){
var self=this;
var left=parseInt(this.wrapperContent.css('left'))-offset
this.wrapperContent.animate({
left:left
},this.data.delay,function(){
if(left<-self.data.num*self.data.img_width){
self.wrapperContent.css({left:-self.data.img_width})
}
if(left>-100){
self.wrapperContent.css({left:-self.data.num*self.data.img_width})
}
})
},
showButton:function(){
this.wrapperButton.eq(this.index-1).addClass('wrapper_on').siblings().removeClass('wrapper_on')
},
play:function(){
var self=this
this.timer=setInterval(function(){
self.wrapperNext.trigger('click')
},2000)
},
stop:function(){
var self=this
clearInterval(self.timer)
}
}
new Slide()
})