點擊表格標題行 (藍色背景),下方詳情行 (紫色背景) 切換顯示/隱藏。純原生 JS,無依賴。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>表格行展開/收起</title>
<style>
table { border-collapse: collapse; width: 760px; }
td { padding: 10px; }
.header-row { background: #00CCFF; cursor: pointer; user-select: none; }
.detail-row { background: #9966FF; display: none; } /* 初始隱藏 */
</style>
</head>
<body>
<table>
<tr class="header-row" onclick="toggleRow('detail1')">
<td>點擊展開詳情 ></td>
</tr>
<tr id="detail1" class="detail-row">
<td>這是詳細內容區域,可以放置表單、圖表、嵌套表格等</td>
</tr>
</table>
<script>
function toggleRow(id) {
var row = document.getElementById(id);
if (!row) return;
// 切換 display: none <-> table-row (或空字符串恢復默認)
row.style.display = (row.style.display === 'none' || row.style.display === '') ? 'table-row' : 'none';
}
</script>
</body>
</html>
display: 'table-row' 而非 block,保持表格布局結構。.detail-row { display: none; } 隱藏,JS 中判斷 '' (初始未設置 inline style) 視為隱藏。cursor: pointer 提示可點擊。// 支持多行、動畫、ARIA
function toggleDetails(btn) {
var expanded = btn.getAttribute('aria-expanded') === 'true';
var targetId = btn.getAttribute('aria-controls');
var $rows = $(targetId).find('tr.detail-row');
$rows.stop().slideToggle(200); // jQuery 動畫
btn.setAttribute('aria-expanded', !expanded);
btn.querySelector('.icon').textContent = expanded ? '▼' : '▲';
}
// HTML
<tr>
<td><button class="header-row" aria-expanded="false" aria-controls="#detailGroup" onclick="toggleDetails(this)">
查看詳情 <span class="icon">▼</span>
</button></td>
</tr>
<tbody id="detailGroup" style="display:none">
<tr class="detail-row">...</tr>
<tr class="detail-row">...</tr>
</tbody>
<details>
<summary>點擊展開詳情</summary>
<table><tr><td>詳細內容...</td></tr></table>
</details>
details summary { cursor: pointer; list-style: none; }
details summary::-webkit-details-marker { display: none; }
details summary::before { content: '▶ '; }
details[open] summary::before { content: '▼ '; }
<details>/<summary> 原生支持展開/收起、鍵盤操作、無障礙、打印樣式,IE 需 Polyfill。