萬盛學電腦網

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

jQuery 實現表格行漸變顯示與隱藏的 More/Less 切換效果

前言

在網頁開發中,當表格數據行數過多時,常採用「漸變顯示」與「漸變隱藏」的交互方式,既能保持介面整潔,又能讓使用者按需查看完整內容。本文將展示如何使用 jQuery 實現一個經典的 More / Less 切換效果:預設只顯示前三行,點擊「More」按鈕逐行淡入顯示剩餘行,點擊「Less」則逐行淡出隱藏多餘行。

核心邏輯

  • 使用 :hidden 與 :visible 選擇器判斷行的可見狀態。
  • 利用 show(2000) 與 hide(2000) 產生 2 秒的漸變動畫。
  • 透過遞迴呼叫實現「逐行」動畫效果。
  • 動態切換按鈕的文字與 onclick 事件,實現 More/Less 狀態切換。

JavaScript 代碼

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(); // 遞迴隱藏上一行
    });
}

HTML 結構

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

使用說明

  1. 引入 jQuery 庫(建議 1.7+ 版本)。
  2. 將上述 JS 代碼放入頁面腳本區塊或外部 .js 檔案。
  3. 確保表格 ID 為 accomplishmenttable,且按鈕緊鄰表格之後(.next() 選擇器依賴此結構)。
  4. 根據需要調整動畫時長(預設 2000ms)與初始顯示行數(邏輯中隱含前 3 行)。

進階優化建議

  • 改用 .on('click', ...) 綁定事件,避免內聯 onclick。
  • 將動畫速度、閾值行數提取為配置參數,提高復用性。
  • 加入 .stop(true, true) 防止快速點擊導致動畫隊列堆疊。
copyright © 萬盛學電腦網 all rights reserved