首頁的商品橫幅、合作夥伴 Logo 牆,往往需要「無縫循環」的效果:滾到尾端後不是空白,而是接回開頭繼續播。本文把這件事封裝成一個可設定的 jQuery 插件。
無縫循環的關鍵只有一句:每次動畫結束後,把已經移出視線的項目搬到尾端(或把尾端項目搬到頭部),再把 left 歸零。因為搬動發生在畫面之外,使用者察覺不到中斷。
(function ($) {
$.fn.extend({
Scroll: function (opt, callback) {
if (!opt) var opt = {};
var _btnleft = $(opt.left);
var _btnright = $(opt.right);
var timerID;
var _this = this.eq(0).find("div").eq(1);
var lineW = _this.find("a:first").width(), // 取得單項寬度
line = opt.line ? parseInt(opt.line, 10) : parseInt(_this.width() / lineW, 10), // 每次滾動項數,預設一屏
speed = opt.speed ? parseInt(opt.speed, 10) : 500; // 速度,數值越大越慢(毫秒)
timer = opt.timer ? parseInt(opt.timer, 10) : 3000; // 自動播放間隔(毫秒)
if (line == 0) line = 1;
var upWidth = 0 - line * lineW;
// 向左滾動
var scrollLeft = function () {
if (!_this.is(":animated")) {
_this.animate({ left: upWidth }, speed, function () {
for (i = 1; i <= line; i++) { _this.find("a:first").appendTo(_this); }
_this.css({ left: 0 });
});
}
}
// 向右滾動
var scrollRight = function () {
if (!_this.is(":animated")) {
for (i = 1; i <= line; i++) { _this.find("a:last").show().prependTo(_this); }
_this.css({ left: upWidth });
_this.animate({ left: 0 }, speed, function () {});
}
}
// 自動播放與滑鼠暫停
var autoPlay = function () { if (timer) timerID = window.setInterval(scrollLeft, timer); };
var autoStop = function () { if (timer) window.clearInterval(timerID); };
_this.hover(autoStop, autoPlay).mouseout();
_btnleft.css("cursor", "pointer").click(scrollLeft).hover(autoStop, autoPlay);
_btnright.css("cursor", "pointer").click(scrollRight).hover(autoStop, autoPlay);
}
})
})(jQuery);
$(document).ready(function () {
$("#scrollable").Scroll({ line: 5, speed: 500, timer: 3000, left: ".prev", right: ".next"});
});
_this.is(":animated") 的判斷可以防止動畫未結束就被再次觸發,避免位置錯亂。hover(autoStop, autoPlay) 讓滑鼠移入時暫停,這是輪播元件的標準體驗設計。左右兩張箭頭圖,以及 jQuery 本體(這就不用多說了):
left.png:

right.png:

樣式部分只需注意三點:div.items 要設 overflow:hidden 與 position:relative,內層 absolute 定位的寬度要給足(示例用 200000em),每個項目則用 float:left 並固定寬高,確保換行不會破壞排版。