在 Excel 中可以做的操作,幾乎都能在網頁上重現,像是拖動複製、Ctrl+C、Ctrl+V 等。這要歸功於 Handsontable 這個強大的 jQuery 插件。它支援 IE7+、Firefox、Chrome、Safari、Opera 等主流瀏覽器。
首先在頁面中引入 jQuery 框架與 Handsontable 的 JS、CSS 檔案,其中以下三個是必要的:
<script src="jquery.min.js"></script> <script src="jquery.handsontable.full.js"></script> <link rel="stylesheet" href="jquery.handsontable.full.css">
接著加入一個用於呈現編輯表格的 DIV 層:
<div id="example1" ></div>
最後對容器進行初始化,可自訂資料、自訂儲存格外觀的渲染函數、核選框欄、自動完成欄等:
//數據
var data = [
{id: 1, name: "Ted", isActive: true, color: "orange"},
{id: 2, name: "John", isActive: false, color: "black"},
{id: 3, name: "Al", isActive: true, color: "red"},
{id: 4, name: "Ben", isActive: false, color: "blue"}
];
//黃色渲染方法
var yellowRenderer = function (instance, td, row, col, prop, value, cellProperties) {
Handsontable.TextCell.renderer.apply(this, arguments);
$(td).css({ background: 'yellow' });
};
//綠色渲染方法
var greenRenderer = function (instance, td, row, col, prop, value, cellProperties) {
Handsontable.TextCell.renderer.apply(this, arguments);
$(td).css({ background: 'green' });
};
//初始化
var $container = $("#example1");
$container.handsontable({
data: data,
startRows: 5,
colHeaders: true,
minSpareRows: 1,
columns: [
{data: "id"},
{data: "name", type: {renderer: yellowRenderer}}, // 黃色渲染
{data: "isActive", type: Handsontable.CheckboxCell}, // 多選框
{data: "color",
type: Handsontable.AutocompleteCell, // 自動完成
source: ["yellow", "red", "orange", "green", "blue", "gray", "black", "white"] // 數據源
}
],
cells: function (row, col, prop) {
if (row === 0 && col === 0) {
return {type: {renderer: greenRenderer}};
}
}
});
把上述設定包進 $(function(){...}) 中即可運行,注意務必在 DIV 容器加載完成後再初始化:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Basic Demo</title>
<script src="jquery.min.js"></script>
<script src="jquery.handsontable.full.js"></script>
<link rel="stylesheet" href="jquery.handsontable.full.css">
<script>
$(function(){
var data = [
{id: 1, name: "Ted", isActive: true, color: "orange"},
{id: 2, name: "John", isActive: false, color: "black"},
{id: 3, name: "Al", isActive: true, color: "red"},
{id: 4, name: "Ben", isActive: false, color: "blue"}
];
// ...yellowRenderer、greenRenderer 與 handsontable 初始化同上...
});
</script>
</head>
<body>
<div id="example1" ></div>
</body>
</html>
Handsontable 幾乎把 Excel 的編輯體驗完整搬到了瀏覽器,非常適合製作需要大量表格編輯的後台系統。