用原生 JavaScript 以物件導向方式封裝滑動選單,好處是呼叫端非常乾淨,樣式與行為完全分離。
var $sliding = document.getElementById("silding");
var s1 = new Sliding();
s1.commands = $sliding.getElementsByTagName("dt");
s1.panels = $sliding.getElementsByTagName("dd");
s1.init("mouseover", "active");
只要給它「標題集合」與「面板集合」,再指定觸發事件與啟用狀態的 class 名稱即可。
<div id="silding" class="silding">
<dl>
<dt class="active">第一個一級菜單</dt>
<dd style="display:block;">
<ul>
<li><a href="#">第一個二級菜單</a></li>
<li>第一個二級菜單</li>
</ul>
</dd>
</dl>
<dl><dt>第二個一級菜單</dt><dd>……</dd></dl>
<dl><dt>第三個一級菜單</dt><dd>……</dd></dl>
</div>
用 dl/dt/dd 而非 div 巢狀,是因為語意上它就是「術語—定義」的對應關係,螢幕閱讀器也能正確理解層級。
function Slider(i, panelHeight) { // 用來記錄「目前展開的是第幾個、高度多少」
this.index = i;
this.panelHeight = panelHeight;
}
function Sliding(activeIndex) {
this.commands = [];
this.panels = [];
this.activeIndex = activeIndex || 0;
this.sliderCache = {};
}
Sliding.prototype = {
// 綁定事件
init: function(eventName, activeCssClass) {
var _this = this;
var cmds = _this.commands;
_this.activeClass = activeCssClass;
for (var i = 0, n = cmds.length; i < n; i++) {
cmds[i]["on" + eventName] = function(e) { _this.handel(this, e); }
cmds[i].index = i;
if (i == _this.activeIndex) {
_this.sliderCache = new Slider(i, _this.panels[i].offsetHeight);
}
}
},
// 事件處理
handel: function(elem, args) {
var _this = this;
var index = elem.index;
var cacheIndex = _this.sliderCache.index;
var cacheElem = _this.commands[cacheIndex];
if (index == cacheIndex) return; // 點自己不做任何事
var showPanel = _this.panels[index];
var hidePanel = _this.panels[cacheIndex];
var h = parseInt(_this.sliderCache.panelHeight);
showPanel.style.height = "0px";
showPanel.style.display = "block";
_this.tween(hidePanel, showPanel, h);
elem.className = _this.activeClass;
cacheElem.className = cacheElem.className.replace(eval("/ ?" + _this.activeClass + " ?/"), "");
_this.sliderCache = new Slider(index, h);
},
// 動畫
tween: function(obj0, obj1, h) {
_this = arguments.callee;
var step = 20;
if ("\v" == "v") { step = 30; } // 舊 IE 偵測
if (h > 0) {
var h0 = obj0.offsetHeight;
var h1 = obj1.offsetHeight;
if (h < step) {
obj0.style.display = "none";
obj0.style.height = (h1 + h) + "px";
obj1.style.height = (h1 + h) + "px";
} else {
h = h - step;
obj0.style.height = (h0 - step) + "px";
obj1.style.height = (h1 + step) + "px";
setTimeout(function() { _this(obj0, obj1, h) }, 50)
}
}
}
}
Slider 這個小類存在的意義是快取「目前展開狀態」:既要知道是哪一個,也要知道它原本多高。滑動時舊面板收合到 0、新面板從 0 展開到原高度,兩者同步進行才有平順的交接感。
cmds[i].index = i 把索引直接掛在 DOM 元素上,是早期避免閉包或 bind 的常見手法。ES5 之後用 bind 會更乾淨。
"\v" == "v" 是經典的 IE 偵測技巧——IE8 及以下會把垂直跳格當成 v 處理。今天不需要了。
eval("/ ?" + ... + " ?/") 這段用 eval 建構正則,完全可以用 new RegExp 取代,而且不必 eval。同理,arguments.callee 在嚴格模式下已被禁用,應改用具名函式運算式。
整體架構是對的:資料(commands/panels)、狀態(sliderCache)、行為(init/handel/tween)各自獨立。把上面幾個 legacy 寫法換掉,這份元件放到今天仍然堪用。