列表中超過三行的內容先摺疊,點「More」逐列淡入展開,點「Less」再逐列淡出收回——這個效果在資訊密度高的頁面很好用。本文用 jQuery 的動畫 API 實作。
function showAccomplishmentTableRow(){
$("#accomplishmenttable tr:hidden").first().show(2000,function(){
showAccomplishmentTableRow();
});
if($("#accomplishmenttable tr:hidden").size()==0){
$("#accomplishmenttable").next().attr("onclick","hideAccomplishmentTableRow()").text("Less");
}
}
function hideAccomplishmentTableRow(){
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 colspan="2">MY ACCOMPLISHMENTS</th>
</tr>
<tr class="bgWhite height40">
<td><div class="margin5">border_bottom1Pgreye7e7e7</div></td>
<td>border_bottom1Pgreye7e7e7</td>
</tr>
<tr class="bgWhite height40">
<td><div class="margin5">border_bottom1Pgreye7e7e7</div></td>
<td>border_bottom1Pgreye7e7e7</td>
</tr>
</tbody>
</table>
<div class="floatR marginT5 p14Font textLink" onclick="showAccomplishmentTableRow();">More</div>
關鍵在遞迴。展開函式每次都只取「下一個隱藏列」做 show(),並在動畫的 callback 裡再次呼叫自己,於是形成一列接一列依序出現的連鎖效果。收合邏輯完全對稱,只是改成取最後一個可見列做 hide(),並保留至少三列作為門檻。同時動態改寫 onclick 與按鈕文字,讓同一個元素在 More/Less 之間雙向切換。
2000 毫秒的單列動畫其實偏慢,五列就要等十秒,實務上建議縮到 200–400 毫秒,或改為整批一次淡入。.size() 在 jQuery 3 已移除,請改用 .length;動態指派 onclick 也不如直接用 .on('click') 綁定來得清楚。
更根本的問題是:用 JS 反覆 show/hide 表格列,對螢幕閱讀器與 SEO 都不友善。若只是「超過 N 筆才摺疊」,純 CSS 加上 :nth-child(n+4) 搭配一個 checkbox 的 hack,或用 <details> 元素,都能做出更好維護、也更無障礙的版本。