點擊標題欄,內容區域以滑動動畫展開/收合,支持多面板獨立控制。
<div id="panel">
<h5 class="head">點擊展開/收合 <span class="icon">▼</span></h5>
<div class="content">
<p>這裡是面板內容,可以放置任意 HTML...</p>
</div>
</div>
#panel { width: 300px; border: 1px solid #0050D0; font-family: sans-serif; }
.head { padding: 10px; background: #96E555; cursor: pointer; user-select: none; position: relative; }
.head::after { content: '▼'; position: absolute; right: 10px; transition: transform .3s; }
.head.active::after { transform: rotate(180deg); }
.content { padding: 15px; border-top: 1px solid #0050D0; display: none; line-height: 1.6; }
$(function() {
$('#panel .head').toggle(function() {
$(this).next('.content').slideUp();
$(this).removeClass('active');
}, function() {
$(this).next('.content').slideDown();
$(this).addClass('active');
});
});
注意:.toggle(fn, fn) 在 jQuery 1.9+ 已移除,建議用寫法二。
$(function() {
$('#panel .head').on('click', function() {
var $content = $(this).next('.content');
var isOpen = $content.is(':visible');
$content.slideToggle(300); // 內部自動判斷方向
$(this).toggleClass('active', !isOpen);
});
});
$(function() {
$('.accordion .head').on('click', function() {
var $panel = $(this).closest('.panel');
var $content = $panel.find('.content');
var isOpen = $content.is(':visible');
// 關閉其他面板
$('.accordion .content:visible').not($content).slideUp(300)
.prev('.head').removeClass('active');
// 切換當前
$content.slideToggle(300);
$(this).toggleClass('active', !isOpen);
});
});
HTML 需包裹:<div class="accordion"><div class="panel">...</div></div>
.stop(true, true) 防止快速點擊排隊role="button" tabindex="0" aria-expanded="false",補充鍵盤 Enter/Space 觸發localStorage 記錄展開面板 ID,刷新恢復.panel > .head 避免事件冒泡干擾<details class="css-panel">
<summary class="head">點擊展開</summary>
<div class="content">內容...</div>
</details>
<style>
.css-panel summary { cursor:pointer; padding:10px; background:#96E555; }
.css-panel[open] summary::after { transform:rotate(180deg); }
.css-panel .content { padding:15px; border-top:1px solid #0050D0; }
</style>
<details>/<summary> 原生支持展開/收合、鍵盤操作、無障礙,IE 需 Polyfill。
面板展開/收合是高頻 UI 模式。jQuery slideToggle 封裝了高度動畫計算,配合狀態類名控制圖標旋轉,代碼極簡。現代項目優先考慮原生 <details> 或 CSS 動畫,僅在需複雜邏輯控制時引入 JS。