* 构造函数初始化及开始轮播
* @param bannnerBox string 包含整个轮播图盒子的id或class
* @param aBox string 包含指示器的盒子的id或class
* @param btnBox string 包含前后按钮的盒子的id或class
*/
function Carousel(bannnerBox, aBox, btnBox) {
this.now = 0;
this.hasStarted = false;
this.interval = null;
this.liItems = null;
this.len = 0;
this.aBox = null;
this.bBox = null;
this.init = function () {
var that = this;
this.liItems = $(bannnerBox).find('ul').find('li');
this.len = this.liItems.length;
this.aBox = $(bannnerBox).find(aBox);
this.bBox = $(bannnerBox).find(btnBox);
this.liItems.first('li').css({
'opacity': 1,
'z-index': 1
}).siblings('li').css({
'opacity': 0,
'z-index': 0
});
var aDom = '';
for (var i = 0; i < this.len; i++) {
aDom += '<a></a>';
}
$(aDom).appendTo(this.aBox);
this.aBox.find('a:first').addClass("indicator-active");
this.bBox.hide();
$(bannnerBox).hover(function () {
that.stop();
that.bBox.fadeIn(200);
}, function () {
that.start();
that.bBox.fadeOut(200);
});
this.aBox.find('a').hover(function () {
that.stop();
var out = that.aBox.find('a').filter('.indicator-active').index();
that.now = $(this).index();
if (out != that.now) {
that.play(out, that.now)
}
}, function () {
that.start();
});
$(btnBox).find('a:first').click(function () {
that.next()
});
$(btnBox).find('a:last').click(function () {
that.prev()
});
}
this.init();
this.start();
}
* 播放函数
* @param out number 要消失的图片的索引值
* @param now number 接下来要轮播的图的索引值
*/
Carousel.prototype.play = function (out, now) {
this.liItems.eq(out).stop().animate({
opacity: 0,
'z-index': 0
}, 500).end().eq(now).stop().animate({
opacity: 1,
'z-index': 1
}, 500);
this.aBox.find('a').removeClass('indicator-active').eq(now).addClass('indicator-active');
}
Carousel.prototype.prev = function () {
var out = this.now;
this.now = (--this.now + this.len) % this.len;
this.play(out, this.now)
}
Carousel.prototype.next = function () {
var out = this.now;
this.now = ++this.now % this.len;
this.play(out, this.now);
}
Carousel.prototype.start = function () {
if (!this.hasStarted) {
this.hasStarted = true;
var that = this;
this.interval = setInterval(function () {
that.next();
}, 2000);
}
}
Carousel.prototype.stop = function () {
clearInterval(this.interval);
this.hasStarted = false;
}
$(function () {
var banner1 = new Carousel('#J_bg_ban1', '#J_bg_indicator1', '#J_bg_btn1');
var banner2 = new Carousel('#J_bg_ban2', '#J_bg_indicator2', '#J_bg_btn2');
});