元件設計目標
- 單一函式支援頁面多組獨立展開/收合區塊
- 點擊標題列切換內容顯示/隱藏
- 圖示自動切換「+」/「-」
- 動畫平滑過渡(
slideToggle)
封裝函式
function initCollapse(triggerSel, iconSel, contentSel) {
$(triggerSel).on('click', function() {
var $trigger = $(this);
var $icon = $trigger.find(iconSel);
var $content = $trigger.siblings(contentSel).first(); // 假設內容為同層下一個
$content.slideToggle(300, function() {
// 動畫完成後切換圖示
$icon.text($content.is(':visible') ? '-' : '+');
});
});
}
// 使用
$(function() {
initCollapse('.slide_show', 'a', '.p-silde');
});
HTML 結構
<ul>
<li>
<div class="slide_show clearfix">
<span style="float:left">我有列表</span>
<a style="float:right">+</a>
</div>
<p class="p-silde" style="display:none">
<a href="#">列表 1</a>
<a href="#">列表 2</a>
<a href="#">列表 3</a>
</p>
</li>
<li>... 第二組 ...</li>
<li>
<div class="slide_show clearfix"><span>我沒有列表</span></div>
<!-- 無 .p-silde,點擊無反應 -->
</li>
</ul>
CSS 輔助
.clearfix::after { content:''; display:table; clear:both; }
.p-silde a { display:block; padding:5px 10px; color:#333; text-decoration:none; }
.p-silde a:hover { background:#f0f0f0; }
進階:支援鍵盤無障礙與 ARIA
function initCollapse(triggerSel, iconSel, contentSel) {
$(triggerSel).attr('role', 'button').attr('tabindex', 0).each(function() {
var $t = $(this), $c = $t.siblings(contentSel).first();
$t.attr('aria-expanded', 'false').attr('aria-controls', $c.attr('id') || 'collapse-' + Math.random().toString(36).substr(2));
if (!$c.attr('id')) $c.attr('id', $t.attr('aria-controls'));
}).on('click keydown', function(e) {
if (e.type === 'keydown' && e.key !== 'Enter' && e.key !== ' ') return;
e.preventDefault();
var $t = $(this), $c = $t.siblings(contentSel).first(), $icon = $t.find(iconSel);
var expanded = $t.attr('aria-expanded') === 'true';
$c.slideToggle(300, function() {
$t.attr('aria-expanded', !expanded);
$icon.text(!expanded ? '-' : '+');
});
});
}