页面中的信息比较多时,需要让信息滚动起来,有的是向上滚有的是向左滚,以下是参考代码:
// 滚动函数 往上滚和往左滚
// opts = {go: 'left', obj: $('.scroll_left'), cons: 5, goTime: 1000, stopTime: 2000, dots: $('.con-dots span')}
// go:滚动方向top/left obj:滚动的容器,有超出隐藏的 cons:容器看到的个数 goTime:滚动的时间,毫秒 stopTime:停止的时间
// dots:滚动的序号按钮,所有的,要设置属性index从0开始(这个参数可不传)
// afterfun:滚动后的函数调用,参数为当前的索引 beforefun:滚动前的函数调用,参数是索引 (这两个函数可不传)
function scrollFun(opts, afterfun, beforefun){
var itemNum = opts.obj.find('li').length;
var conH = opts.obj.innerHeight();
var conW = opts.obj.innerWidth();
var itemH = conH/opts.cons;
var itemW = conW/opts.cons;
var cur = 1;
opts.obj.find('li').clone().appendTo(opts.obj.find('ul')).attr('mark', 'clone');
// 上滚
var toTop = function(){
if(typeof beforefun == 'function'){
beforefun(cur == itemNum? 0: cur);
}
opts.obj.stop(true, true).animate({
scrollTop: itemH*cur+'px'
}, opts.goTime, function(){
if(typeof afterfun == 'function'){
afterfun(cur == itemNum? 0: cur);
}
if(opts.dots)
opts.dots.eq(cur == itemNum? 0: cur).addClass('active').siblings().removeClass('active');
cur++;
if(cur > itemNum){
opts.obj.stop(true, true).scrollTop(0);
cur = 1;
}
})
}
if(opts.go == 'top'){
var timer = setInterval(toTop, opts.stopTime)
opts.obj.on('mouseover', function(){
clearInterval(timer);
})
opts.obj.on('mouseout', function(){
timer = setInterval(toTop, opts.stopTime)
})
if(opts.dots){
opts.dots.on('mouseover', function(){
clearInterval(timer);
var index = $(this).attr('index');
cur = index == 0? itemNum : index;
toTop();
})
opts.dots.on('mouseout', function(){
timer = setInterval(toTop, opts.stopTime)
})
}
}
// 左滚
var toLeft = function(){
if(typeof beforefun == 'function'){
beforefun(cur == itemNum? 0: cur);
}
opts.obj.stop(true, true).animate({
scrollLeft: itemW*cur+'px'
}, opts.goTime, function(){
if(typeof afterfun == 'function'){
afterfun(cur == itemNum? 0: cur);
}
if(opts.dots)
opts.dots.eq(cur == itemNum? 0: cur).addClass('active').siblings().removeClass('active');
cur++;
if(cur > itemNum){
opts.obj.stop(true, true).scrollLeft(0);
cur = 1;
}
})
}
if(opts.go == 'left'){
opts.obj.find('ul').css('width', itemW*itemNum*2+'px');
var timer = setInterval(toLeft, opts.stopTime);
opts.obj.on('mouseover', function(){
clearInterval(timer);
})
opts.obj.on('mouseout', function(){
timer = setInterval(toLeft, opts.stopTime)
})
if(opts.dots){
opts.dots.on('mouseover', function(){
clearInterval(timer);
var index = $(this).attr('index');
cur = index == 0? itemNum : index;
toLeft();
})
opts.dots.on('mouseout', function(){
timer = setInterval(toLeft, opts.stopTime)
})
}
}
}