後台管理介面裡的表格,往往不只是把資料攤開就好。使用者會想點一下標題排序、雙擊某格直接改內容、把重要的欄位拖到左邊、再把備註欄拉寬一點。這份以原生 JavaScript 寫成的表格元件,把這四件事全部做進去,而且沒有依賴任何函式庫。
點擊表頭排序:數值、字串、日期三種型別可指定,同一欄再點一次即反向排序,並以箭頭符號標示目前排序方向。
雙擊編輯:可編輯的欄位才會附加 edit 屬性,編輯規則可以是正則表達式,也可以是自訂的驗證函式,不通過就跳提示並把焦點留在輸入框。
拖曳換列:按住表頭拖到目標欄位,放開即完成整列的搬移,表頭索引會同步重新標記。
拖曳縮放欄寬:欄位右側的把手可左右拖動,並以最小寬度 minWidth 作為下界,拖動過程中有一條輔助線即時預覽。
表格本身語意清楚:thead 放表頭、tbody 放資料列。表頭每格內含一個 span(顯示文字與排序箭頭)與一個 class="r dr" 的 div(縮放把手)。
<table id="tab" border="0" cellspacing="1" cellpadding="0"> <thead> <tr> <td width="80" class="tc"><span class="l">ID</span><div class="r dr"></div></td> <td width="130" class="tc"><span class="l">姓名</span><div class="r dr"></div></td> <td width="130" class="tc"><span class="l">生日</span><div class="r dr"></div></td> <td width="220" class="tc"><span class="l">備註</span><div class="r dr"></div></td> </tr> </thead> <tbody> <tr> <td>1</td><td>小三</td><td>1982-05-27</td><td>杯具,全是杯具</td> </tr> <tr> <td>3</td><td>李四</td><td>1983-06-27</td><td>魔獸技術不錯</td> </tr> <tr> <td>2</td><td>王五</td><td>1987-05-27</td><td>波斯王子</td> </tr> </tbody> </table>
原始範例的 tbody 共有十一列示範資料,這裡節錄三列。樣式部分有幾個關鍵:邊框用 border-collapse: collapse 收合;.dr 靠 float:right 加負 margin 貼在儲存格右緣,游標設為 sw-resize;.div 與 .line 是拖曳時才顯示的定位提示元素。
建構子接收表格元素與一份設定陣列,每個設定物件用 id 指出欄位索引、type 指定排序型別,需要編輯的欄位再加上 edit 規則與提示訊息。
var Table = new Class({
options : { minWidth : 62 },
initialize : function(tab, set){
this.table = tab;
this.rows = []; // 所有 tr 的引用,排序時使用
this.sortCol = null; // 目前排序中的欄位
this.inputtd = null; // 目前被編輯的 td
this.editconfig = {}; // 各欄的編輯規則與提示
this.thead = tab.getElementsByTagName('thead')[0];
this.theadTds = this.thead.getElementsByTagName('td');
this.tbodyTds = tab.getElementsByTagName('tbody')[0].getElementsByTagName('td');
this.closConfig = { on:false, td:null, totd:null }; // 拖曳換列狀態
this.widthConfig = { td:null, nexttd:null, x:0, tdwidth:0, nexttdwidth:0 };
Extend(this, this.options);
// 不指定寬度的話 chrome 與 ie6 會亂跳
(Sys.ie6 || Sys.chrome) && (tab.width = tab.offsetWidth);
// ie6 做 dom 操作時不會記住核取狀態,得自己存一份
if(Sys.ie6){
this.checkbox = {};
var checkboxs = tab.getElementsByTagName('input'), i = 0, l = checkboxs.length;
for(; i < l; i++)
(checkboxs[i].type == "checkbox" || checkboxs[i].type == "radio") &&
addListener(checkboxs[i], "click", Bind(this, function(elm, i){
elm.checked == true ? (this.checkbox[i] = elm) : (delete this.checkbox[i]);
}, checkboxs[i], i));
}
var i = 0, l = set.length,
rows = tab.tBodies[0].rows,
d = document,
tabTads = tab.getElementsByTagName('td'),
length = this.theadTds.length;
// 唯一共用的編輯用 input
this.input = d.createElement('input');
this.input.type = "text";
this.input.className = 'edit';
this.div = d.body.appendChild(d.createElement('div')); // 拖曳提示方塊
this.div.className = "div";
this.line = d.body.appendChild(d.createElement('div')); // 縮放提示線
this.line.className = 'line';
this.line.style.top = objPos(tab).y + "px";
for(; i < l; i++){
addListener(this.theadTds[set[i].id], 'click',
Bind(this, this.sortTable, this.theadTds[set[i].id], set[i].type));
set[i].edit && (this.editconfig[set[i].id] =
{ rule:set[i].edit.rule, message:set[i].edit.message });
}
for(i = 0, l = rows.length; i < l; i++) this.rows[i] = rows[i];
for(i = 0, l = tabTads.length; i < l; i++){
i < length && tabTads[i].setAttribute('clos', i); // 表頭記號
i >= length && this.editconfig[i % length] &&
tabTads[i].setAttribute('edit', i % length); // 可編輯記號
}
addListener(this.thead, 'mousedown', BindAsEventListener(this, this.dragOrWidth));
addListener(this.thead, 'mouseover', BindAsEventListener(this, this.theadHover));
addListener(this.thead, 'mouseout', BindAsEventListener(this, this.theadOut));
addListener(tab, 'dblclick', BindAsEventListener(this, this.edit));
addListener(this.input, 'blur', Bind(this, this.save, this.input));
},
排序前先把所有 tr 存進陣列,排序後用 DocumentFragment 一次塞回 tbody,避免逐筆操作造成的多次重排。同一欄再點一次只反轉陣列,不重新排序,省下一趟比較。
sortTable : function(td, type){
var frag = document.createDocumentFragment(),
span = td.getElementsByTagName('span')[0],
str = span.innerHTML;
if(td === this.sortCol){
this.rows.reverse();
span.innerHTML = str.replace(/.$/, str.charAt(str.length - 1) == "↓" ? "↑" : "↓");
}else{
this.rows.sort(this.compare(td.getAttribute('clos'), type));
span.innerHTML = span.innerHTML + "↑";
this.sortCol != null && (this.sortCol.getElementsByTagName('span')[0].innerHTML =
this.sortCol.getElementsByTagName('span')[0].innerHTML.replace(/.$/, ''));
}
for(var i = 0, l = this.rows.length; i < l; i++) frag.appendChild(this.rows[i]);
this.table.tBodies[0].appendChild(frag);
if(Sys.ie6){
for(var s in this.checkbox) this.checkbox[s].checked = true;
}
this.sortCol = td;
},
compare : function(n, type){
return function(a1, a2){
var convert = {
int : function(v){ return parseInt(v) },
float : function(v){ return parseFloat(v) },
date : function(v){ return v.toString() },
string : function(v){ return v.toString() }
};
!convert[type] && (convert[type] = function(v){ return v.toString() });
a1 = convert[type](a1.cells[n].innerHTML);
a2 = convert[type](a2.cells[n].innerHTML);
return a1 == a2 ? 0 : a1 < a2 ? -1 : 1;
};
},
編輯時把同一個 input 節點搬進被點的 td,失去焦點就依規則驗證。規則可以是正則,也可以是回傳 true 或錯誤訊息字串的函式;函式回傳字串時,該字串會取代原本的提示內容。
edit : function(e){
var elem = this.inputtd = e.srcElement || e.target;
if(!elem.getAttribute('edit')) return;
this.input.value = elem.innerHTML;
elem.innerHTML = "";
elem.appendChild(this.input);
this.input.focus();
},
save : function(elem){
var editinfo = this.editconfig[elem.parentNode.getAttribute('edit')],
status = {
"[object Function]" : 'length' in editinfo.rule && editinfo.rule(this.input.value) || false,
"[object RegExp]" : 'test' in editinfo.rule && editinfo.rule.test(this.input.value) || false
}[Object.prototype.toString.call(editinfo.rule)],
_self = this;
typeof status != "boolean" && (editinfo.message = status);
if(status === true){
this.inputtd.innerHTML = this.input.value;
this.inputtd = null;
}else{
alert(editinfo.message);
// firefox 下直接 focus 不會生效,用 setTimeout 才行
setTimeout(function(){ _self.input.focus() }, 0);
}
},
兩件事共用同一個 mousedown 入口,靠事件目標的節點名稱分流:點到 td 就是拖曳,點到 div(把手)就是縮放。拖曳期間在 document 上掛 mousemove/mouseup,放開時全部移除,並用 setCapture(IE)或 preventDefault 避免選取到文字。
dragOrWidth : function(e){
var elem = e.srcElement || e.target, widthConfig = this.widthConfig;
if(elem.nodeName.toLowerCase() === 'td'){
this.closConfig.td = elem.getAttribute('clos');
addListener(document, 'mousemove', BindAsEventListener(this, this.dragMove));
addListener(document, 'mouseup', Bind(this, this.dragUp));
this.closConfig.on = true;
Sys.ie ? this.thead.setCapture(false) : e.preventDefault();
}
if(elem.nodeName.toLowerCase() === 'div'){
Sys.ie ? (e.cancelBubble = true) : e.stopPropagation();
// 最後一格右邊沒有隔壁欄,不縮放
if(this.theadTds[this.theadTds.length - 1] === elem.parentNode) return;
Sys.ie ? this.thead.setCapture(false) : e.preventDefault();
widthConfig.x = e.clientX;
widthConfig.td = elem.parentNode;
widthConfig.nexttd = widthConfig.td.nextSibling;
while(widthConfig.nexttd.nodeName.toLowerCase() != "td"){
widthConfig.nexttd = widthConfig.nexttd.nextSibling;
}
widthConfig.tdwidth = widthConfig.td.offsetWidth;
widthConfig.nexttdwidth = widthConfig.nexttd.offsetWidth;
this.line.style.height = this.table.offsetHeight + "px";
addListener(document, 'mousemove', BindAsEventListener(this, this.widthMove));
addListener(document, 'mouseup', Bind(this, this.widthUp));
}
},
dragMove : function(e){
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
setStyle(this.div, { display:"block", left:e.clientX + 9 + "px", top:e.clientY + 20 + "px" });
},
dragUp : function(){
var closConfig = this.closConfig,
rows = this.table.getElementsByTagName('tr'),
td, n, o, i = 0, l = rows.length;
this.div.style.display = "none";
removeListener(document, 'mousemove');
removeListener(document, 'mouseup');
Sys.ie && this.thead.releaseCapture();
closConfig.on = false;
if(closConfig.totd === null) return;
removeClass(this.theadTds[closConfig.totd], 'thover');
if(closConfig.td === closConfig.totd) return; // 同一欄不處理
// 決定插入方向
if(closConfig.td * 1 + 1 === closConfig.totd * 1){
n = closConfig.totd; o = closConfig.td;
}else{
n = closConfig.td; o = closConfig.totd;
}
for(; i < l; i++){
td = rows[i].getElementsByTagName('td');
rows[i].insertBefore(td[n], td[o]);
}
// 表頭記號重新編號
for(i = 0, l = this.theadTds.length; i < l; i++)
this.theadTds[i].setAttribute('clos', i);
closConfig.totd = closConfig.td = null;
},
widthMove : function(e){
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
var widthConfig = this.widthConfig,
x = e.clientX - widthConfig.x,
left = e.clientX, clientX = left;
if(clientX < widthConfig.x &&
widthConfig.x - clientX > widthConfig.tdwidth - this.minWidth){
left = widthConfig.x - widthConfig.tdwidth + this.minWidth;
}
if(clientX > widthConfig.x &&
clientX - widthConfig.x > widthConfig.nexttdwidth - this.minWidth){
left = widthConfig.x + widthConfig.nexttdwidth - this.minWidth;
}
setStyle(this.line, { display:"block", left:left + "px" });
},
widthUp : function(){
this.line.style.display = "none";
var widthConfig = this.widthConfig,
x = parseInt(this.line.style.left) - widthConfig.x;
widthConfig.nexttd.style.width = widthConfig.nexttdwidth - x - 1 + 'px';
widthConfig.td.style.width = widthConfig.tdwidth + x - 1 + 'px';
Sys.ie && this.thead.releaseCapture();
removeListener(document, 'mousemove');
removeListener(document, 'mouseup');
}
window.onload = function(){
function checkName(val){
if(val.replace(/^\s+$/g, '') === '') return '姓名輸入不能為空';
if(val.replace(/^\s+|\s+$/, '').length > 10) return '姓名長度不能大於10個字符';
if(!/^[\u4e00-\u9fa5a-z]+$/i.test(val)) return '姓名只能輸入中文或者是字母';
return true;
}
function checkRemark(val){
if(val.replace(/^\s+$/g, '') === '') return '備注輸入不能為空';
if(val.replace(/^\s+|\s+$/, '').length > 15) return '備注長度不能大於15個字符';
if(!/^[\u4e00-\u9fa5\w\s]+$/i.test(val)) return '備注只能輸入中文數字下劃線空格';
return true;
}
var set = [
{ id:0, type:"int" },
{ id:1, type:"string", edit:{ rule:checkName, message:'' } },
{ id:2, type:"date", edit:{ rule:/^\d{4}\-\d{2}\-\d{2}$/, message:"請輸入 1985-02-30 這樣的格式" } },
{ id:3, type:"string", edit:{ rule:checkRemark, message:'' } }
];
new Table($("tab"), set);
}
這份元件寫於需要兼顧 IE6 的年代,因此保留了一些歷史包袱,實測到的狀況有:IE6 下中文不會自動換行;非 IE 瀏覽器遇到連續英文字母與數字同樣不換行;在 Chrome 中直接線上執行時行為不太穩定,存到本機開啟會正常得多。
若要在今天的專案裡沿用同樣的互動,建議保留它的思路而更換實作手段:用 requestAnimationFrame 取代拖曳中的直接 style 寫入以減少重排;把 mousemove 上的重疊與邊界計算改為節流處理;用 dataset 取代 setAttribute('clos') 這類自訂屬性;排序若要處理大量資料,比較函式可先抽取 key 再排序(decorate-sort-undecorate)以避免重複轉型。觀念是通用的,工具則可以一直換新。