萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實現表格行展開/收起切換:點擊標題行顯示隱藏詳情行

效果演示

點擊表格標題行 (藍色背景),下方詳情行 (紫色背景) 切換顯示/隱藏。純原生 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,保持表格布局結構。
  • 初始狀態用 CSS .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>

現代 CSS Only 方案 (無 JS)

<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。

copyright © 萬盛學電腦網 all rights reserved