一般的圖片輪播多半是平面地左右滑動,而這個範例則透過調整每張圖的 width、height、left、top 與 z-index,讓中間的圖最大最前、兩側的圖遞減並向後退,營造出有景深的立體感,視覺上更為吸睛。
var forimg = function (foritem, hoverStop, defaultfor) {
var _foritem = foritem.constructor == jQuery ? foritem : $(foritem);
var imgarr = [
{ "z-index": 1, "width": 100, "height": 100, "left": 0, "top": "75px" },
{ "z-index": 2, "width": 200, "height": 200, "left": 50, "top": "25px" },
{ "z-index": 3, "width": 300, "height": 250, "left": 150, "top": "0" },
{ "z-index": 2, "width": 200, "height": 200, "left": 370, "top": "25px" },
{ "z-index": 1, "width": 100, "height": 100, "left": 520, "top": "75px" }
];
// 初始化每張圖的樣式
_foritem.each(function (i) {
var _this = $(this);
_this.css(imgarr[i] || imgarr[4]);
_this.find("img").css(imgarr[i] || imgarr[4]);
});
// 依位移量批次套用動畫
var _for = function (_i, data, nulldata, callback) {
$(foritem).each(function (i) {
var self = $(this);
setTimeout(function () {
self.css("z-index", (data[i + _i] || nulldata)["z-index"])
self.stop().animate(data[i + _i] || nulldata);
self.find("img").stop().animate(data[i + _i] || nulldata, function () {
callback.call(self, i);
});
});
});
};
// 自動輪播
var that = this;
var defaultforfun = function () {
if (!defaultfor) { that.leftfor(); }
else { that.rightfor(); }
};
var forimgInterval = setInterval(defaultforfun, 1000);
if (hoverStop) {
_foritem.hover(function () {
clearInterval(forimgInterval);
}, function () {
forimgInterval = setInterval(defaultforfun, 1000);
});
}
// 向左輪播:把第一張移到最後
this.leftfor = function () {
var nuldata = { "z-index": -1, "width": 100, "height": 100, "left": 520, "top": "75px" };
_for(-1, imgarr, nuldata, function (i) {
if (i == 0) { this.closest("ul").append(this); }
});
};
// 向右輪播:把最後一張移到最前
this.rightfor = function () {
var nuldata = { "z-index": -1, "width": 100, "height": 100, "left": 0, "top": "75px" };
_for(1, imgarr, nuldata, function (i) {
if (i == _foritem.length - 1) {
this.closest("ul").prepend(this);
this.css("z-index", "1");
}
});
};
this.stop = function () { clearInterval(forimgInterval); };
this.next = function () { forimgInterval = setInterval(defaultforfun, 1000); };
};
這支函式的巧思在於用一個 imgarr 陣列定義「每個位置該有的樣式」——從最左到最右,寬高與層級呈現「小、中、大、中、小」的對稱配置,於是畫面自然浮現立體感。輪播時,leftfor 與 rightfor 會搭配 _for 批次套用動畫,並在動畫結束後,把移動到頭尾的元素重新 append 或 prepend 回列表,形成無縫循環。此外還支援 hoverStop(滑入暫停)與 stop、next 等控制方法,讓你能自由整合進各式展示情境。