topic description
use a subclass because you want to add a subclass that fades in and out of the carousel, so the common method is placed in the parent class. The if judgment at the beginning of autoplay feels a bit troublesome and wants to be separated by multiple functions, but it is written to find that there are more callbacks. Is it better to make more repetitive code or write a callback?
related codes
/ / Please paste the code text below (do not replace the code with pictures)
; (function (window, document) {
let defaultSetting = { //
"interval": 2000
}
class Carousel {
/*
*@param userSetting
*/
constructor(userSetting) {
let self = this;
self.setting = Object.assign(defaultSetting, userSetting); //
self.warp = $(self.setting.warp); //
self.imgBox = self.warp.find(".img-box"); //
self.dots = self.warp.find(".dot-box").children().children(); //
self.lBtn = self.warp.find(".direction").children().eq(0); //
self.rBtn = self.warp.find(".direction").children().eq(1); //
self.len = self.imgBox.children().length; //
self.timer = null; //
self.bool = true;
this.warp.mouseenter(function() {
self.stop();
self.lBtn.fadeIn(200);
self.rBtn.fadeIn(200);
})
this.warp.mouseleave(function(){
self.start()
self.lBtn.fadeOut(200);
self.rBtn.fadeOut(200);
})
this.dots.click(function(){
self.autoPlay(null,$(this).index())
})
};
start(){
this.timer = setInterval(this.autoPlay.bind(this),this.setting.interval)
};
stop(){
clearInterval(this.timer)
};
dotChange(index){
this.dots.eq(index).addClass("active").siblings().removeClass("active");
}
}
class silde extends Carousel {
constructor(userSetting) {
super(userSetting)
this.init();
};
init() {
let self = this;
//
self.width = self.warp.width()
//
self.index = 1;
self.cloned()
self.rBtn.click(function() {
self.autoPlay()
});
self.lBtn.click(function() {
self.autoPlay("left")
let imgBox = self.imgBox
if(self.index > 0){
self.index--
}else{
self.index = self.len
}
console.log(self.index);
self.move(imgBxo,self.index)
})
//
self.start()
};
cloned() {
let self = this;
let first = self.imgBox.children("li:first-child").clone(true);
let last = self.imgBox.children("li:last-child").clone(true);
self.imgBox.append(first)
self.imgBox.prepend(last)
};
/*
* @param direction
* @param index
*
*/
autoPlay(direction, index) {
let self = this;
if(self.bool) {
self.bool = false;
if(index != undefined){
self.index = index+1;
}else{
if(direction != "left") {
self.indexPP
} else {
self.index--
}
}
self.imgBox.animate({
"margin-left": self.index * -(self.width) + "px"
}, 300, function() {
if(self.index > self.len) {
//
self.index = 1;
self.imgBox.css({
"margin-left": self.index * -(self.width) + "px"
})
}
if(self.index < 1) {
//
self.index = self.len;
self.imgBox.css({
"margin-left": self.index * -(self.width) + "px"
})
}
//
self.dotChange(self.index-1);
self.bool = true;
})
}
};
}
window.silde = silde;
}) (window, document)
let s = new silde ({
)"warp": "-sharpmyCarousel"
})