點擊表頭任意位置即可左右拖拽調整列寬,同列所有行寬度同步變化,最小寬度限制 10px,文字永不被表格線覆蓋,適合數據網格場景。
<td> 寬度聯動,保持對齊<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD><TITLE>表格列拖拽</TITLE>
<script language="javascript">
var colnum = 0, begin_x, begin_y, drag_flag = false;
document.onmousedown = mouseDragBegin;
document.onmousemove = mouseDrag;
document.onmouseup = mouseDragEnd;
function setDrag(col) { drag_flag = true; colnum = col; }
function mouseDragBegin() {
if (drag_flag) { begin_x = event.x; begin_y = event.y; }
}
function mouseDrag() {
if (!drag_flag || window.event.button != 1) return;
var now_x = event.x, delta = now_x - begin_x;
var targetCols;
switch (colnum) {
case 0: targetCols = ColRight1; break;
case 1: targetCols = ColRight2; break;
case 2: targetCols = ColRight3; break;
case 3: targetCols = ColRight4; break;
default: return;
}
var newW = targetCols[0].style.pixelWidth + delta;
if (newW < 10) newW = 10;
for (var i = 0; i < targetCols.length; i++)
targetCols[i].style.pixelWidth = newW;
begin_x = now_x;
}
function mouseDragEnd() { drag_flag = false; }
</script>
</HEAD><BODY>
<TABLE ID="tblTitle" BORDER=0 cellspacing=0 cellpadding=0
STYLE="border-collapse:collapse;">
<tr height=30>
<td class="tdTitle"><DIV ID=ColRight1 style="width:100px;background:red" unselectable="on" onMouseDown="setDrag(0)">000</DIV></td>
<td class="tdTitle"><DIV ID=ColRight2 style="width:100px;background:green" unselectable="on" onMouseDown="setDrag(1)">111</DIV></td>
<td class="tdTitle"><DIV ID=ColRight3 style="width:120px;background:red" unselectable="on" onMouseDown="setDrag(2)">222</DIV></td>
<td class="tdTitle"><DIV ID=ColRight4 style="width:50px;background:green" unselectable="on" onMouseDown="setDrag(3)">333</DIV></td>
</tr>
<tr height=30>
<td class="tdTitle"><DIV ID=ColRight1 style="width:100px;background:red" unselectable="on" onMouseDown="setDrag(0)">000</DIV></td>
<td class="tdTitle"><DIV ID=ColRight2 style="width:100px;background:green" unselectable="on" onMouseDown="setDrag(1)">111</DIV></td>
<td class="tdTitle"><DIV ID=ColRight3 style="width:120px;background:red" unselectable="on" onMouseDown="setDrag(2)">222</DIV></td>
<td class="tdTitle"><DIV ID=ColRight4 style="width:50px;background:green" unselectable="on" onMouseDown="setDrag(3)">333</DIV></td>
</tr>
</TABLE>
</BODY></HTML>
| 技巧 | 作用 |
|---|---|
unselectable="on" | 防止拖拽時文字被選中(IE) |
| 同 ID 多元素 | 利用 document.all['ColRight1'] 隱式數組特性,一次遍歷同列所有行 |
style.pixelWidth | 直接操作像素數值,避免字符串解析 |
border-collapse:collapse | 合併邊框,視覺無縫隙 |
class 而非重複 ID,配合 querySelectorAlladdEventListener,區分 mousedown/mousemove/mouseupelement.style.width = 'px'requestAnimationFrame 優化重繪