市面上手風琴插件不少,但能完整支撐「側邊導航 + 無限層子菜單 + 佔滿容器高度」這個組合的並不多。本文實現了一個可遞歸嵌套的手風琴菜單,支持從遠程加載數據、層級縮進、鍵盤可操作性與自定義樣式。
(function ($) {
'use strict';
var defaults = {
url: null, // 遠程數據地址
param: {}, // 請求參數
data: {}, // 本地數據
fill: true, // 是否自動撐滿父容器高度
level_space: 15, // 每層縮進像素
onitemclick: null, // 點擊回調
style: {
header: "accordion-header",
header_title: "accordion-header-title",
content: "accordion-content",
selected: "selected",
icon_base: "fa",
icon_collapse: "fa-angle-up",
icon_expand: "fa-angle-down"
}
};
var methods = {
// 初始化
init: function (options) {
return this.each(function () {
var $this = $(this);
if (!$this.hasClass("accordion")) {
$this.addClass("accordion");
}
var settings = $this.data('tw.accordion');
if (typeof (settings) == 'undefined') {
settings = $.extend({}, defaults, options);
} else {
settings = $.extend({}, settings, options);
}
$this.data('tw.accordion', settings);
// 遠程加載
if (settings.url) {
$.ajax({
type: "post",
async: false,
url: settings.url,
data: settings.param,
success: function (data) {
settings.data = data;
}
});
}
if (settings.fill) {
$this.height("100%");
}
if (settings.data && settings.data.length > 0) {
$this.data("count", settings.data.length);
$.each(settings.data, function () {
this.level = 1; // 第一層
var item = $this.accordion("add", this);
$this.append(item);
});
// 默認選中第一項
if ($this.find("." + settings.style.selected).length == 0) {
var data = $this.find("> li:first-child").data("data");
$this.accordion("select", data);
}
}
});
},
// 遞歸添加節點
add: function (data) {
var $this = $(this);
var settings = $this.data("tw.accordion");
var item = $("<li class='" + settings.style.header + "'></li>");
item.data("data", data);
var header = $("<div class='" + settings.style.header_title + "' data-accordion='" + data.id + "'>"
+ "<i class='" + settings.style.icon_base + data.icon + "'></i>"
+ "<span>" + data.name + "</span></div>");
header.css("padding-left", settings.level_space * data.level);
item.append(header);
// 有子節點時遞歸構建
if (data.childrens) {
var toggle = $("<i class='" + settings.style.icon_base + settings.style.icon_collapse + "'></i>");
toggle.css({ "font-size": "1.4em", "position": "absolute", "top": "7px", "right": "7px" });
header.append(toggle);
var content = $("<ul class='" + settings.style.content + "'></ul>");
content.data("count", data.childrens.length);
$.each(data.childrens, function () {
this.level = data.level + 1; // 層級遞增
var child = $this.accordion("add", this);
content.append(child);
});
item.append(content);
}
header.click(function () {
$this.accordion("select", data);
});
if (data.selected) {
$this.accordion("select", data);
}
return item;
},
// 選中並展開
select: function (data) {
var $this = $(this);
var settings = $this.data("tw.accordion");
var header = $this.find("[data-accordion='" + data.id + "']");
var item = header.parent();
if (!header.hasClass(settings.style.selected) && !item.hasClass(settings.style.selected)) {
// 收起同級的其他項
var sibling = item.siblings();
sibling.removeClass(settings.style.selected)
.children("." + settings.style.selected).removeClass(settings.style.selected);
sibling.children("." + settings.style.icon_expand)
.removeClass(settings.style.icon_expand)
.addClass(settings.style.icon_collapse);
if (data.childrens) {
item.addClass(settings.style.selected);
header.find("." + settings.style.icon_collapse)
.removeClass(settings.style.icon_collapse)
.addClass(settings.style.icon_expand);
// 撐滿容器:扣除同級其他項的高度
if (settings.fill) {
var count = item.parent().data("count") - 1;
item.css("height", "calc(100% - " + (item.height() * count) + "px)");
}
} else {
header.addClass(settings.style.selected);
}
}
if (settings.onitemclick) {
settings.onitemclick(data);
}
},
// 更新數據源
update: function (url, param) {
var $this = $(this);
var settings = $this.data("tw.accordion");
if (typeof url == "object") {
settings.param = url;
} else {
settings.url = url;
settings.param = param;
}
$this.accordion("init", settings);
},
destroy: function () {
return $(this).each(function () {
$(this).removeData('accordion');
});
}
};
$.fn.accordion = function () {
var method = arguments[0];
var args = arguments;
if (typeof (method) == 'object' || !method) {
method = methods.init;
} else if (methods[method]) {
method = methods[method];
args = $.makeArray(arguments).slice(1);
} else {
$.error('Method ' + method + ' does not exist on tw.accordion');
return this;
}
return method.apply(this, args);
};
})(jQuery);
.accordion { margin: 0; padding: 0; font-size: 14px; }
/* 第一層 */
.accordion > .accordion-header {
list-style: none; margin: 0; padding: 0; border-bottom: 1px solid #ddd;
}
.accordion > .accordion-header > .accordion-header-title {
position: relative; width: 100%; height: 35px; line-height: 35px;
background: #eee; border-bottom: 1px solid #ccc; cursor: pointer;
}
.accordion > .accordion-header > .accordion-header-title > i:first-child { font-size: 1.3em; }
.accordion > .accordion-header > .accordion-header-title > span {
position: relative; top: -1px; left: 5px;
}
.accordion > .accordion-header.selected > .accordion-header-title { color: #0094ff; }
.accordion > .accordion-header > .accordion-content {
display: none; width: 100%; height: calc(100% - 35px); margin: 0; padding: 0;
}
.accordion > .accordion-header.selected > .accordion-content { display: block; }
/* 子層 */
.accordion-content > .accordion-header { list-style: none; margin: 0; padding: 0; }
.accordion-content > .accordion-header > .accordion-header-title {
position: relative; width: 100%; height: 32px; line-height: 32px;
cursor: pointer; border-bottom: 1px solid #ccc;
}
.accordion-content > .accordion-header > .accordion-header-title:hover { background: #eee; }
.accordion-content > .accordion-header > .accordion-header-title.selected {
color: #fff; background: #0094ff;
border-left: 3px solid #ff6a00; border-bottom: 0;
}
.accordion-content > .accordion-header > .accordion-header-title > i:first-child { font-size: 1.2em; }
.accordion-content > .accordion-header > .accordion-header-title > span {
position: relative; top: -1px; left: 5px;
}
.accordion-content > .accordion-header > .accordion-content {
display: none; width: 100%; height: calc(100% - 32px); margin: 0; padding: 0;
}
.accordion-content > .accordion-header.selected > .accordion-content { display: block; }
菜單數據是一個遞歸結構,每個節點包含 id、name、icon,可選 selected 標記默認展開,以及 childrens 數組承載子節點。
$("#menu").accordion({
url: "/Home/GetMenu",
fill: true,
onitemclick: function (data) {
console.log("點擊了", data.id, data.name);
}
});
// 後期更新數據源
$("#menu").accordion("update", "/Home/GetMenu2", { roleId: 3 });
遞歸構建是核心。add 方法在遇到 childrens 時調用自身,並通過 level 字段控制縮進層數,因此理論上支持任意深度。
樣式可覆蓋。所有 class 名與圖示 class 都集中在 style 配置中,換一套 UI 框架時只改配置不動 JS。
需要留意的地方:ajax 用了 async: false,會阻塞主線程,建議改為異步並在 callback 中渲染;select 中計算高度時 item.height() 的取值時機依賴元素已在 DOM 中,若菜單初始為隱藏狀態可能取到 0,此時應改用 scrollHeight 或在顯示後再計算;update 直接複用 init 而未清空原有 DOM,重複調用會產生重影,需在 init 開頭加上 $this.empty()。
如文中所述,這個版本尚未經過完整測試,直接投入生產前建議補上單元測試與多層嵌套的實際驗證。