萬盛學電腦網

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

jQuery 將 Table 轉為可編輯 Excel 風格表格:ManualTable 插件解析

將靜態 HTML <table> 轉為可編輯、可調整列寬、隔行變色、懸停高亮的 Excel 風格表格,是後台管理常見需求。本文解析 ManualTable 插件核心邏輯與擴展點。

插件功能特性

  • 自動將 td 轉為 <input readonly> 模擬單元格
  • 隔行變色(可配置)
  • 行懸停高亮(可配置)
  • 指定列居中/可編輯(移除 readonly)
  • 列寬拖拽調整(滑動條可視化)
  • 表頭游標提示可調整列

HTML 調用示例

<table id="GridTable">
    <thead>
        <th>員工編號</th><th>姓名</th><th>工作部門</th><th>職務</th>
        <th>家庭住址</th><th>聯系電話</th><th>手機</th><th>備注</th>
    </thead>
    <tbody>
        <tr><td>456456</td><td>456456</td><td>456456</td><td>456456</td>
            <td>456456</td><td>456456</td><td>456456</th><td>456456</td>
        </tr>
        <!-- 更多行 -->
    </tbody>
</table>

<script>
$(document).ready(function() {
    $("#GridTable").ManualTable({
        // ChangeAction: function() { ... } // 單元格變更回調
    });
});
</script>

核心源碼邏輯解析

1. 默認配置與合併

$.fn.ManualTable = function(options) {
    var opts = $.extend({}, $.fn.ManualTable.defaults, options);
    // defaults 包含:BorderColor, ThBackColor, ThHeight, TableFontSize, 
    // TdHeight, TdColor, TdBackColor, IsODDChange, ChangeColor1, 
    // IsMoveChange, ChangeColor2, CenterIndex[], EditIndex[]
};

2. 基礎樣式初始化


// 表格整體
$(this).css({
    "border-collapse": "collapse",
    "border-spacing": 0,
    "width": "100%",
    "border": "solid " + opts.BorderColor + " 1px",
    "font-size": opts.TableFontSize
});

// 表頭
$("#" + tabid + " th").css({
    "background": opts.ThBackColor,
    "border-left": "solid " + opts.BorderColor + " 1px",
    "height": opts.ThHeight,
    "color": opts.ThColor
});

// 數據行單元格
$("#" + tabid + " td").css({
    "border-left": "solid " + opts.BorderColor + " 1px",
    "height": opts.TdHeight,
    "border-top": "solid " + opts.BorderColor + " 1px",
    "padding": "0",
    "color": opts.TdColor,
    "background": opts.TdBackColor
});

// 首列無左邊框
$("#" + tabid + " th:first-child, #" + tabid + " td:first-child").css("border-left", "none");

3. 核心轉換:td → input[readonly]

var str = $("#" + tabid + " td").html();
$("#" + tabid + " td").html(
    "<input style='width:100%; border:none; height:100%; vertical-align:middle' " +
    "value='" + str + "' readonly/>"
);

// 統一 input 樣式
$("#" + tabid + " input").css({
    "background-color": opts.TdBackColor,
    "color": opts.TdColor
});

4. 隔行變色

if (opts.IsODDChange) {
    $("#" + tabid + " tr:even").find("input").css("background-color", opts.ChangeColor1);
}

5. 懸停高亮

if (opts.IsMoveChange) {
    $("#" + tabid + " tr").hover(
        function() { $(this).find("input").css("background", opts.ChangeColor2); },
        function() { $(this).find("input").css("background", opts.TdBackColor); }
    );
}

6. 指定列居中 / 可編輯


$.each($("#" + tabid + " tr"), function() {
    // 居中列
    for (var i = 0; i < opts.CenterIndex.length; i++) {
        $(this).find("input").eq(opts.CenterIndex[i]).css("text-align", "center");
    }
    // 可編輯列(移除 readonly)
    for (var i = 0; i < opts.EditIndex.length; i++) {
        $(this).find("input").eq(opts.EditIndex[i]).removeAttr("readonly");
    }
});

7. 列寬拖拽調整(核心難點)


// 拖拽指示線
$("body").append('');

$("body").on("mousemove", function(e) {
    if (lineMove) $("#markline").css("left", e.clientX).show();
});

$("#" + tabid + " th").on("mousemove", function(e) {
    var $th = $(this);
    var left = $th.offset().left;
    var width = $th.width();
    var isFirst = $th.prevAll().length < 1;
    var isLast = $th.nextAll().length < 1;
    
    // 判斷滑鼠是否在邊緣 4px 內
    var nearLeft = (e.clientX - left) < 4;
    var nearRight = (width - (e.clientX - left)) < 4;
    
    if ((isFirst && nearRight) || (isLast && nearLeft) || (!isFirst && !isLast && (nearLeft || nearRight))) {
        $th.css("cursor", "col-resize");
    } else {
        $th.css("cursor", "default");
    }
}).on("mousedown", function(e) {
    var $th = $(this);
    var pos = $th.offset();
    // 確定調整哪一列(左側邊緣調整前一列,右側調整當前列)
    // 設置 lineMove=true,記錄 currTh,顯示 markline
    // mousemove 中更新 markline 位置
    // mouseup 時計算新寬度,應用到 th/td,銷毀 markline
});

配置選項完整列表

選項 類型 默認值 說明
BorderColor String "#ccc" 邊框顏色
ThBackColor String "#eee" 表頭背景
ThHeight String "25px" 表頭高度
TdHeight String "22px" 數據行高度
IsODDChange Boolean true 是否隔行變色
ChangeColor1 String "#f9f9f9" 偶數行背景
IsMoveChange Boolean true 是否懸停高亮
ChangeColor2 String "#eef" 懸停背景
CenterIndex Array<Number> [] 居中列索引(0-based)
EditIndex Array<Number> [] 可編輯列索引

局限與改進方向

  • ❌ 不支持單元格合併(rowspan/colspan)
  • ❌ 不支持巢狀表格
  • ❌ 大數據量(>500行)渲染性能差,需虛擬滾動
  • ❌ 拖拽邏輯較複雜,易有邊界 bug
  • ✅ 改進:重寫為 Canvas/WebGL(如 Handsontable、AG Grid)
  • ✅ 改進:使用 contenteditable 替代 input,減少 DOM 節點

現代替代方案推薦

庫 特點 適用場景
Handsontable Excel-like、豐富 API、商業授權 複雜電子表格應用
AG Grid 企業級、虛擬滾動、React/Vue/Angular 綁定 大數據網格、商業項目
Tabulator 輕量、無依賴、功能全 中型項目、快速開發
x-spreadsheet 純 JS、Excel 兼容、開源 在線試算表

結語

ManualTable 展示了「漸進增強」思路:以語義化 HTML 為基礎,JS 增強交互。理解其「td→input、樣式注入、事件委託、拖拽調度」核心流程,有助於閱讀、維護或重構類似組件。新項目建議直接採用成熟表格庫,避免重複造輪子。

copyright © 萬盛學電腦網 all rights reserved