萬盛學電腦網

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

jQuery 實現 Table 隔行變色、懸停高亮、點擊選中行效果

表格行交互(斑馬紋、懸停、選中)是後台管理系統的基礎體驗。本文提供一套完整、可復用的 jQuery 實現方案,兼容動態數據渲染場景。

HTML 結構規範

<table class="list" width="99%" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#c0de98">
    <thead>
        <tr class="table-tr-title">
            <th width="5%">標題</th>
            <th width="5%">標題</th>
            <th width="5%">標題</th>
            <th width="5%">標題</th>
        </tr>
    </thead>
    <tbody>
        <tr class="table-tr-content"><td>數據</td><td>數據</td><td>數據</td><td>數據</td></tr>
        <tr class="table-tr-content"><td>數據</td><td>數據</td><td>數據</td><td>數據</td></tr>
        <!-- 更多行 -->
    </tbody>
</table>

CSS 樣式定義

<style>
.table-tr-title { height: 26px; font-size: 12px; text-align: center; }
.table-tr-content { height: 18px; text-align: center; font-size: 12px; }

/* 斑馬紋:偶數行(從數據第1行算起) */
.normalEvenTD { background: #DFD8D8; } /* 第1、3、5...行 */
.normalOddTD  { background: #FFFFFF; } /* 第2、4、6...行 */

/* 懸停態 */
.hoverTD { background-color: #eafcd5; height: 18px; text-align: center; font-size: 12px; }

/* 選中態 */
.trSelected { background-color: #51b2f6; height: 18px; text-align: center; font-size: 12px; color: #fff; }
</style>

jQuery 核心邏輯

$(function() {
    var $tables = $(".list");
    
    $tables.each(function() {
        var $table = $(this);
        
        // 1. 初始化斑馬紋:跳過表頭
        // :even/:odd 相對於匹配集合索引(0-based)
        $("tr:not(:first)", $table).filter(":even").addClass("normalEvenTD"); // 索引 0,2,4... 對應第1、3、5行
        $("tr:not(:first)", $table).filter(":odd").addClass("normalOddTD");   // 索引 1,3,5... 對應第2、4、6行
        
        // 2. 懸停高亮(排除表頭)
        $("tr:not(:first)", $table).hover(
            function() {
                $(this).addClass("hoverTD").removeClass("normalEvenTD normalOddTD");
            },
            function() {
                $(this).removeClass("hoverTD");
                // 恢復斑馬紋:需判斷原本奇偶
                var index = $("tr:not(:first)", $table).index(this);
                $(this).addClass(index % 2 === 0 ? "normalEvenTD" : "normalOddTD");
            }
        );
        
        // 3. 點擊選中行(排除表頭)
        $("tr:not(:first)", $table).click(function() {
            var $tr = $(this);
            // 移除其他行選中態
            $table.find(".trSelected").removeClass("trSelected");
            // 添加當前行選中態
            $tr.addClass("trSelected");
            // 可在此觸發業務事件
            // $(document).trigger("rowSelected", [$tr.data("id"), $tr]);
        });
    });
});

關鍵邏輯解析

1. 斑馬紋索引計算

$("tr:not(:first)") 排除表頭後,:even 對應集合中索引 0,2,4... 即視覺上第 1、3、5 行數據行。這比 tr:even(包含表頭)更直觀。

2. 懸停狀態恢復

移除 hoverTD 後,必須根據行索引恢復正確的斑馬紋類,否則會出現顏色錯亂。

3. 選中態互斥

先 .find(".trSelected").removeClass() 再 .addClass(),保證單選語義。

動態數據渲染後的重新綁定

AJAX 獲取數據重繪 tbody 後,需重新調用初始化邏輯。建議封裝為函數:

function initTableInteractions($table) {
    $table = $table || $(".list");
    // ... 上述完整邏輯
}

// AJAX 成功回調
$.get("/api/data", function(html) {
    $(".list tbody").html(html);
    initTableInteractions(); // 重新綁定
});

進階:支持多選與鍵盤導航

// 多選:Ctrl/Cmd + 點擊
$("tr:not(:first)", $table).click(function(e) {
    var $tr = $(this);
    if (e.ctrlKey || e.metaKey) {
        $tr.toggleClass("trSelected");
    } else {
        $table.find(".trSelected").removeClass("trSelected");
        $tr.addClass("trSelected");
    }
});

// 鍵盤上下鍵導航(需表格聚焦)
$table.attr("tabindex", 0).keydown(function(e) {
    var $selected = $table.find(".trSelected").first();
    var $rows = $("tr:not(:first)", $table);
    var idx = $rows.index($selected);
    if (e.key === "ArrowDown" && idx < $rows.length - 1) {
        $selected.removeClass("trSelected");
        $rows.eq(idx + 1).addClass("trSelected").focus();
    } else if (e.key === "ArrowUp" && idx > 0) {
        $selected.removeClass("trSelected");
        $rows.eq(idx - 1).addClass("trSelected").focus();
    }
});

現代 CSS 替代方案(無 JS 斑馬紋/懸停)

/* 純 CSS 斑馬紋 */
.list tbody tr:nth-child(odd)  { background: #DFD8D8; }
.list tbody tr:nth-child(even) { background: #FFFFFF; }

/* 純 CSS 懸停 */
.list tbody tr:hover { background-color: #eafcd5; }

/* 選中態仍需 JS 切換類 */
.list tbody tr.trSelected { background-color: #51b2f6; color: #fff; }

優勢:無 JS 依賴、渲染更快、無閃爍。JS 僅負責選中態切換與業務事件觸發。

結語

表格行交互看似簡單,細節決定體驗:斑馬紋索引基準、懸停恢復邏輯、選中態互斥、動態重綁、多選/鍵盤輔助。封裝為可配置插件($.fn.tableUI(options))可進一步提升復用率。

copyright © 萬盛學電腦網 all rights reserved