DIV CSS 佈局教程網

把 table 變成可編輯試算表的 ManualTable 插件
編輯:JQuery特效代碼     

後台系統常需要「像 Excel 一樣可直接在表格上編輯」的介面。ManualTable 這個 jQuery 插件把原生 table 妝點成可編輯表格,還支援拖曳調整欄寬、隔行變色與滑鼠移入高亮。

頁面部分

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="ManualTable2.js"></script>
<title>無標題文檔</title>
<script>
$(document).ready(function(e) {
  $("#GridTable").ManualTable({
    // ChangeAction: function(){
    //   var inputs = $(this).parent().parent().find("input");
    //   alert(inputs.length);
    // }
  });
});
</script>
</head>

<body >
<table id="GridTable">
<thead>
<th>員工編號</th>
<th>姓名</th>
<th>工作部門</th>
<th>職務</th>
<th>家庭住址</th>
<th>聯繫電話</th>
<th>手機</th>
<th>備註</th>
</thead>
<tr>
<td>456456</td>
<td>456456</td>
<td>456456</td>
<td>456456</td>
<td>456456</td>
<td>456456</td>
<td>456456</td>
<td>456456</td>
</tr>
<!-- 其餘資料列結構相同,此處省略 -->
</table>

</body>
</html>

插件原始碼

這是依前人腳本修改擴充的版本,加了幾個功能,對初學者理解插件寫法也有些幫助。它對原生 table 友善,但不支援 table 內含其他複雜元素。

// 這個腳本主要起裝飾作用,支援原生 table,但不支援 table 內有其他元素
(function ($) {
  $.fn.ManualTable = function (options) {
    var tabid = $(this).attr("id");
    var lineMove = false;
    var currTh = null;
    var opts = $.extend({}, $.fn.ManualTable.defaults, options);

    $(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"
    });

    // 把每個 td 的內容包進 input,模擬試算表的儲存格
    var str = $("#" + tabid + " td").html();
    $("#" + tabid + " td").html("<input style='width:100%; border:none; height:100%;vertical-align:middle' value='" + str + "' readonly/>");

    $("#" + tabid + " input").css({
      "background-color": opts.TdBackColor,
      "color": opts.TdColor
    });
    if (opts.IsODDChange) {
      $("#" + tabid + " tr:even").find("input").css({
        "background-color": opts.ChangeColor1
      });
    }
    if (opts.IsMoveChange == true) {
      $("#" + tabid + " tr").hover(function () {
        $(this).find("input").css("background", opts.ChangeColor2);
      }, function () {
        $(this).find("input").css("background", opts.TdBackColor);
      });
    }
    $.each($("#" + tabid + " tr"), function () {
      for (var i = 0; i < opts.CenterIndex.length; i++) {
        $(this).find("input").eq(opts.CenterIndex[i]).css({
          "text-align": "center"
        });
      }
      for (var i = 0; i < opts.EditIndex.length; i++) {
        $(this).find("input").eq(opts.EditIndex[i]).removeAttr("readonly");
      }
    });

    // 拖曳調整欄寬用的輔助線
    $("body").append("<div id=\"markline\" style=\"width:1px;height:200px;border-left:1px solid #999; position:absolute;display:none\" ></div> ");
    $("body").bind("mousemove", function (event) {
      if (lineMove == true) {
        $("#markline").css({
          "left": event.clientX
        }).show();
      }
    });

    $("#" + tabid + " th").bind("mousemove", function (event) {
      $("body").attr({
        onselectstart: "event.returnValue=false"
      });
      var th = $(this);
      var left = th.offset().left;

      if (th.prevAll().length < 1) {
        if ((th.width() - (event.clientX - left)) < 4) {
          th.css({ 'cursor': 'col-resize' });
        } else {
          th.css({ 'cursor': 'default' });
        }
      } else if (th.nextAll().length < 1) {
        if (event.clientX - left < 4) {
          th.css({ 'cursor': 'col-resize' });
        } else {
          th.css({ 'cursor': 'default' });
        }
      } else {
        if (event.clientX - left < 4 || (th.width() - (event.clientX - left)) < 4) {
          th.css({ 'cursor': 'col-resize' });
        } else {
          th.css({ 'cursor': 'default' });
        }
      }
    });

    $("#" + tabid + " th").bind("mousedown", function (event) {
      var th = $(this);
      var pos = th.offset();
      if (th.prevAll().length < 1) {
        if ((th.width() - (event.clientX - pos.left)) < 4) {
          var height = th.parent().parent().parent().height();
          var top = pos.top;
          $("#markline").css({
            "height": height,
            "top": top,
            "left": event.clientX,
            "display": ""
          });
          lineMove = true;
          if (event.clientX - pos.left < th.width() / 2) {
            currTh = th.prev();
          } else {
            currTh = th;
          }
        }
      } else if (th.nextAll().length < 1) {
        if (event.clientX - pos.left < 4) {
          var height = th.parent().parent().parent().height();
          var top = pos.top;
          $("#markline").css({
            "height": height,
            "top": top,
            "left": event.clientX,
            "display": ""
          });
          lineMove = true;
          if (event.clientX - pos.left < th.width() / 2) {
            currTh = th.prev();
          } else {
            currTh = th;
          }
        }
      } else {
        if (event.clientX - pos.left < 4 || (th.width() - (event.clientX - pos.left)) < 4) {
          var height = th.parent().parent().parent().height();
          var top = pos.top;
          $("#markline").css({
            "height": height,
            "top": top,
            "left": event.clientX,
            "display": ""
          });
          lineMove = true;
          if (event.clientX - pos.left < th.width() / 2) {
            currTh = th.prev();
          } else {
            currTh = th;
          }
        }
      }
    });

    $("body").bind("mouseup", function (event) {
      $("body").removeAttr("onselectstart");
      if (lineMove == true) {
        $("#markline").hide();
        lineMove = false;
        var pos = currTh.offset();
        var index = currTh.prevAll().length;
        currTh.width(event.clientX - pos.left);
        $(this).find("tr").each(function () {
          $(this).children().eq(index).width(event.clientX - pos.left);
        });
      }
    });

    $("#" + tabid + " tr").bind(opts.RowsType, opts.RowsClick);
    $("#" + tabid + " input").bind("change", opts.ChangeAction);
    $("#" + tabid + " input").focus(function (e) {
      $(this).css({ "border": "none" })
    });

    $("#" + tabid + " th").bind("mouseup", function (event) {
      $("body").removeAttr("onselectstart");
      if (lineMove == true) {
        $("#markline").hide();
        lineMove = false;
        var pos = currTh.offset();
        var index = currTh.prevAll().length;
        currTh.width(event.clientX - pos.left);
        currTh.parent().parent().find("tr").each(function () {
          $(this).children().eq(index).width(event.clientX - pos.left);
        });
      }
    });
  };

  $.fn.ManualTable.defaults = {
    UpDataUrl: "Updata.do",     // 編輯更新資料的遠端請求位址(可省略)
    TableFontSize: "12px",      // 表格字型大小
    ThBackColor: "#005AD2",     // 表頭背景色
    ThColor: "#fff",            // 表頭文字色
    ThHeight: "30px",           // 表頭高度
    TdBackColor: "#FFF",        // 儲存格背景色
    TdColor: "red",             // 儲存格文字色
    TdHeight: "20px",           // 儲存格高度
    BorderColor: "#555",        // 表格邊框顏色
    IsODDChange: false,         // 是否隔行變色(與滑鼠移入變色不可同時使用)
    ChangeColor1: "#ff0",       // 隔行變色顏色
    IsMoveChange: true,         // 是否滑鼠移入變色
    ChangeColor2: "#00f",       // 滑鼠移入變色顏色
    CenterIndex: [3, 4, 5, 6],  // 置中欄位 index,從 0 開始
    EditIndex: [2, 3, 5],       // 可編輯欄位 index,從 0 開始

    // 編輯觸發函式:自動更新並儲存資料
    ChangeAction: function () {
      var basepath = $.fn.ManualTable.defaults.UpDataUrl;
      var tds = $(this).parent().parent().find("input");
      var str = "";
      $.each(tds, function (i) {
        str += str == "" ? "arg" + i + "=" + $(this).val() : "&arg" + i + "=" + $(this).val();
      });
      alert(basepath + "?" + str);
      // $.get($.fn.ManualTable.defaults.UpDataUrl + "?" + str, function(data){
      //   alert(data);
      // });
    },

    // 資料列觸發設定
    IsRowsClick: true,
    RowsType: "dblclick",
    RowsClick: function () {
      alert($.fn.ManualTable.defaults.UpDataUrl);
    }
  };
})(jQuery);

設計重點

整個插件的核心只有一行:把每個 td 的內容包進一個 <input>,預設 readonly,再由 EditIndex 決定哪些欄位可以編輯。这样一来,編輯體驗就與試算表相似,但底層仍是原生表格。

欄寬拖曳則靠三個元素合作:th 的 mousemove 判斷滑鼠是否在邊界 4px 內並切換游標、markline 顯示對齊輔助線、mouseup 時把新寬度套用到該欄的所有 td。

使用時要留意

  • 表格結構必須簡單,th 要放在 thead 內,td 內不要再放其他元素,否則 html() 取值會出錯。
  • onselectstart 是 IE 專屬屬性,其他瀏覽器需改用 CSS 的 user-select:none 才能防止拖曳時選到文字。
  • 預設的 ChangeAction 把參數直接拼進網址,正式環境請改用 $.ajax 的 POST 並在後端做驗證與參數化查詢。
  • 大量資料列時,逐一包裹 input 會明顯拖慢,建議搭配虛擬捲動或分頁。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved