下面是一個封裝成插件的多行滾動示例,支持定時自動滾動與上下翻動按鈕:
(function($){
$.fn.extend({
Scroll:function(opt,callback){
if(!opt) var opt={};
var _btnUp = $("#"+ opt.up);
var _btnDown = $("#"+ opt.down);
var timerID;
var _this=this.eq(0).find("ul:first");
var lineH=_this.find("li:first").height(),
line=opt.line?parseInt(opt.line,10):parseInt(this.height()/lineH,10),
speed=opt.speed?parseInt(opt.speed,10):500;
timer=opt.timer;
if(line==0) line=1;
var upHeight=0-line*lineH;
var scrollUp=function(){
_btnUp.unbind("click",scrollUp);
_this.animate({
marginTop:upHeight
},speed,function(){
for(i=1;i<=line;i++){ _this.find("li:first").appendTo(_this); }
_this.css({marginTop:0});
_btnUp.bind("click",scrollUp);
});
}
var scrollDown=function(){
_btnDown.unbind("click",scrollDown);
for(i=1;i<=line;i++){ _this.find("li:last").show().prependTo(_this); }
_this.css({marginTop:upHeight});
_this.animate({
marginTop:0
},speed,function(){
_btnDown.bind("click",scrollDown);
});
}
var autoPlay = function(){ if(timer)timerID = window.setInterval(scrollUp,timer); };
var autoStop = function(){ if(timer)window.clearInterval(timerID); };
_this.hover(autoStop,autoPlay).mouseout();
_btnUp.css("cursor","pointer").click( scrollUp ).hover(autoStop,autoPlay);
_btnDown.css("cursor","pointer").click( scrollDown ).hover(autoStop,autoPlay);
}
})
})(jQuery);
$(document).ready(function(){
$("#scrollDiv").Scroll({line:4,speed:500,timer:3000,up:"btn2",down:"btn1"});
});
這段代碼的運作原理可以分幾點來理解:
1. 容器 #scrollDiv 高度限制為 100px,每行 25px,只能顯示 4 行,但裡面有 8 行。通過 overflow:hidden 把超出的部分隱藏。
2. 至於哪 4 行顯示,靠的是 _this.find("li:first").appendTo(_this):把前面滾出去的行依次剪切到後面,同時把 marginTop 歸零,於是始終只顯示當前的 4 行;向下翻動則用 _this.find("li:last").prependTo(_this) 反向操作。
3. animate 是 jQuery 的動畫函數,負責平滑滾動。而 _btnDown.unbind("click",scrollDown) 之所以要「綁定後又解開」,是為了在動畫執行期間避免重複點擊造成混亂,等滾動完成後再重新綁定。
4. 不點擊時也會自動滾動,是因為 _this.hover(autoStop,autoPlay) 這句:hover 是 jQuery 常用方法,第一個參數是鼠標移入時觸發(這裡用來停止自動播放),第二個參數是移出時觸發(恢復自動播放)。
5. 調用時傳入的 opt 是一個對象,包含每次滾動行數 line、速度 speed、間隔 timer 以及上下按鈕的 id,插件據此完成初始化。