「點一下標題,明細內容就展開;再點一下又收回去」是很常見的表格互動。實作起來只需要一個切換 display 的小函式,把觸發事件綁在標題列上即可。
核心只有一個函式:取得目標列,檢查目前的 style.display,是空字串就設為 none 隱藏,否則還原為空字串讓它回歸預設的顯示狀態。然後在標題列的 tr 上掛 onclick,把明細列的 id 傳進去。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS 實現滑鼠點擊展開/隱藏表格列</title>
</head>
<body>
<script language="javascript">
// 傳入目標列的 id,即可在展開與收合之間切換
function TestBlack(TagName) {
var obj = document.getElementById(TagName);
if (obj.style.display == "") {
obj.style.display = "none";
} else {
obj.style.display = "";
}
}
</script>
<table width="760" border="0" cellspacing="0" cellpadding="0">
<tr onclick="TestBlack('divc');">
<td width="760" height="20" bgcolor="#00CCFF">Click Me!</td>
</tr>
<tr id="divc">
<td width="760" height="60" bgcolor="#9966FF"></td>
</tr>
</table>
</body>
</html>
這個寫法勝在簡短,但實際專案裡通常還需要補上幾件事:
1. 視覺提示:在標題列加一個箭頭圖示,展開時轉 180 度,讓使用者知道目前狀態;
2. 無障礙:把 onclick 換成真正的 <button> 並搭配 aria-expanded,鍵盤使用者才能操作;
3. 動畫:想加上高度過渡效果時,display 無法做 transition,需改用 max-height 搭配 overflow: hidden;
4. 多列聯動:若有多組明細,把 id 改成用 this.nextElementSibling 取得相鄰列,就不需要為每列寫死 id。
希望本文所述對大家的 JavaScript 程式設計有所幫助。