有人可以帮我优化这个javascript代码吗? 我看到重复了。我可以避免这种重复吗?
谢谢!
var billboardTimer;
var billboardCurrent = 0;
var billboardSize = $('.billboard li').size();
$('.billboard li').on('click', function(){
clearInterval(billboardTimer);
$('.billboard li').removeClass('active');
$(this).addClass('active');
$('.billboard .img-large').removeClass('current').removeAttr('style');
$('.billboard .img-large').eq($(this).index()).animate({'opacity': 1}).show();
});
$('.billboard li:first').click();
billboardTimer = setInterval(billboardNext, 2000);
function billboardNext(){
billboardCurrent++;
if (billboardCurrent == billboardSize) {billboardCurrent = 0;}
$('.billboard .img-large').removeClass('current').removeAttr('style');
$('.billboard .img-large').eq(billboardCurrent).animate({'opacity': 1}).show();
$('.billboard li').removeClass('active');
$('.billboard li').eq(billboardCurrent).addClass('active');
}
答案 0 :(得分:0)
也许是这样的?
var billboardTimer;
var billboardCurrent = 0;
var billboardSize = $('.billboard li').size();
$('.billboard li').on('click', function(){
clearInterval(billboardTimer);
setActive($(this).index());
});
$('.billboard li:first').click();
billboardTimer = setInterval(function() {
setActive(billboardCurrent = (billboardCurrent + 1) % billboardSize);
}, 2000)
function setActive(index) {
$('.billboard .current').animate({'opacity': 0}).removeClass('current');;
$('.billboard .img-large').eq(index).animate({ 'opacity': 1}).addClass('current');
$('.billboard li').removeClass('active').eq(index).addClass('active');
}