在網頁開發中,當表格數據行數過多時,常採用「漸變顯示」與「漸變隱藏」的交互方式,既能保持介面整潔,又能讓使用者按需查看完整內容。本文將展示如何使用 jQuery 實現一個經典的 More / Less 切換效果:預設只顯示前三行,點擊「More」按鈕逐行淡入顯示剩餘行,點擊「Less」則逐行淡出隱藏多餘行。
:hidden 與 :visible 選擇器判斷行的可見狀態。show(2000) 與 hide(2000) 產生 2 秒的漸變動畫。onclick 事件,實現 More/Less 狀態切換。function showAccomplishmentTableRow() {
$("#accomplishmenttable tr:hidden").first().show(2000, function() {
showAccomplishmentTableRow(); // 遞迴顯示下一行
});
if ($("#accomplishmenttable tr:hidden").size() == 0) {
// 所有行已顯示,切換按鈕為 Less
$("#accomplishmenttable").next().attr("onclick", "hideAccomplishmentTableRow()").text("Less");
}
}
function hideAccomplishmentTableRow() {
// 若可見行數 ≤ 3,直接切換為 More
if ($("#accomplishmenttable tr:visible").size() <= 3) {
$("#accomplishmenttable").next().attr("onclick", "showAccomplishmentTableRow()").text("More");
return;
}
// 從最後一行開始隱藏
$("#accomplishmenttable tr:visible").last().hide(2000, function() {
hideAccomplishmentTableRow(); // 遞迴隱藏上一行
});
}
<table id="accomplishmenttable" class="bgWhite border3PGreye7e7e7 marginT20 roundedCorner width100P">
<tbody>
<tr class="bgLightGreyf5f5f5 height40">
<th class="border_bottom3Pgreye7e7e7 border_right1Pgreye7e7e7 border_top1PWhite fontGreyGeneral textCenter roundedCorner_TL verticalMiddle width30P" colspan="2">MY ACCOMPLISHMENTS</th>
</tr>
<tr class="bgWhite height40">
<td class="border_bottom1Pgreye7e7e7 border_right1Pgreye7e7e7 fontGreyGeneral p14Font width20P">
<div class="margin5">border_bottom1Pgreye7e7e7</div>
</td>
<td class="border_bottom1Pgreye7e7e7 border_right1Pgreye7e7e7 fontGreyGeneral p14Font textLeft width80P">
border_bottom1Pgreye7e7e7
</td>
</tr>
<tr class="bgWhite height40">
<td class="border_bottom1Pgreye7e7e7 border_right1Pgreye7e7e7 fontGreyGeneral p14Font width20P">
<div class="margin5">border_bottom1Pgreye7e7e7</div>
</td>
<td class="border_bottom1Pgreye7e7e7 border_right1Pgreye7e7e7 fontGreyGeneral p14Font textLeft width80P">
border_bottom1Pgreye7e7e7
</td>
</tr>
</tbody>
</table>
<div class="floatR marginT5 p14Font textLink" onclick="showAccomplishmentTableRow();">More</div>
accomplishmenttable,且按鈕緊鄰表格之後(.next() 選擇器依賴此結構)。.on('click', ...) 綁定事件,避免內聯 onclick。.stop(true, true) 防止快速點擊導致動畫隊列堆疊。