專案裡需要一個手風琴式的橫向展開效果。網路上現成的 jQuery 手風琴插件不少,但實際比對下來總覺得有些笨重,配置項又多又用不上。與其花時間讀別人的源碼,不如自己寫一個——脈絡清楚,後續要擴充也方便。
核心原理其實很單純:容器設為相對定位並隱藏溢出,內部每個項目設為絕對定位,然後透過計算每個項目該停留的 left 值來排列。滑鼠移入某項時,讓該項保持完整寬度,其餘項目壓縮,總寬度剛好填滿容器。
;(function($) {
/**
* 基於 jQuery 的簡易手風琴切換插件
*/
$.fn.iAccordion = function(iSet) {
var self = this;
iSet = $.extend({
Type: 'mouseover', // 觸發方式
Select: 'img', // 需要切換的元素選擇器
Cur: 0, // 預設展開項的索引
InitInterval: 100, // 初始化動畫間隔
Interval: 500, // 互動動畫間隔
Easing: '' // 需 jQuery.easing 支援
}, iSet || {});
var item, boxW, selectW, animateW, sIndex, animateL;
$(self).each(function() {
// 初始化容器樣式
$(this).css({ 'position': 'relative', 'overflow': 'hidden' });
item = $(this).find(iSet.Select);
// 初始化切換元素樣式
item.css({ 'position': 'absolute', 'left': 0, 'top': 0 });
boxW = $(this).outerWidth();
selectW = item.outerWidth();
// 每個收合狀態項目的寬度
animateW = (boxW - selectW) / (item.size() - 1);
// 初始化排列,並為每個項目掛上索引
item.each(function(i) {
$(this).animate({ 'left': animateW * i + 'px' },
iSet.InitInterval, iSet.Easing);
$(this).data('index', i);
}).on(iSet.Type, function(e) {
// 取出當前項目索引
sIndex = $(this).data('index');
// 依索引大小關係決定排列位置
item.each(function(n) {
n > sIndex
? animateL = selectW + animateW * (n - 1)
: animateL = animateW * n;
$(this).stop().animate({ 'left': animateL + 'px' },
iSet.Interval, iSet.Easing);
});
}).eq(iSet.Cur).trigger(iSet.Type);
});
}
})(jQuery);
$(selectMain).iAccordion({...});Type:滑鼠事件類型,可填 mouseover、click、mouseleave 等。Select:選擇器,用來抓取需要參與切換的元素集合。Cur:預設展開元素的索引,從 0 起算。InitInterval:頁面載入時的初始化動畫間隔。Interval:滑鼠觸發時的動畫間隔。Easing:動畫緩動效果,需要額外引入 jQuery.easing 插件。若要使用 Easing 參數,記得先載入 jQuery.easing 插件,參數值就是該插件的方法名稱,例如 easeOutBounce、easeOutQuint 等。
另外,程式碼中的 item.size() 在 jQuery 3.0 已被移除,若使用新版本 jQuery,請改寫為 item.length。