有些時候我們希望表格中的某一行默認隱藏,點擊標題行後再展開或收起,用一點原生JavaScript操作style就能實現。核心思路是切換目標元素style.display的值。
完整程式碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS實現鼠標點擊展開/隱藏表格行</title>
</head>
<body>
<script language="javascript">
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>
關鍵在TestBlack函數:它先用getElementById拿到要控制的行,再判斷該行當前style.display是否為空——如果為空(即可見),就設成none隱藏;否則設回空字符串恢復顯示。配合onclick事件綁定在標題行上,點一下即可在展開與隱藏之間切換。這種做法輕量、無需依賴任何庫,適合簡單的表格交互場景。