col-resize 游標。<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>可拖曳調整欄寬的表格</title>
<style>
table { border-collapse: collapse; width: 100%; font-family: sans-serif; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: center; }
th { background: #f0f0f0; cursor: default; user-select: none; position: relative; }
th.resizing { cursor: col-resize !important; }
</style>
</head>
<body>
<h2>拖曳表頭右邊緣調整欄寬</h2>
<table id="resizableTable">
<thead>
<tr>
<th style="width:100px;">用戶編號</th>
<th>試用時間</th>
<th>轉正時間</th>
<th>性別</th>
<th>姓名拼音</th>
<th>生日時間</th>
<th>民族</th>
<th>身高</th>
</tr>
</thead>
<tbody>
<tr><td>2000001</td><td>1997-3-13</td><td>1997-3-13</td><td>1</td><td>WZJ</td><td>1965-3-13</td><td>漢</td><td>171</td></tr>
<tr><td>2000045</td><td>2001-2-15</td><td>2001-3-15</td><td>0</td><td>WY</td><td>1978-8-5</td><td>漢</td><td>162</td></tr>
<tr><td>2000046</td><td>2001-2-23</td><td>2001-3-23</td><td>0</td><td>LQ</td><td>2001-2-23</td><td>漢</td><td>171</td></tr>
</tbody>
</table>
<script>
const table = document.getElementById('resizableTable');
const headerCells = table.querySelectorAll('th');
let dragCell = null; // 正在拖曳的表頭儲存格
let startX = 0; // 滑鼠按下時的 clientX
let startWidth = 0; // 該儲存格初始寬度
headerCells.forEach(th => {
// 滑鼠移動:偵測是否靠近右邊緣
th.addEventListener('mousemove', e => {
if (dragCell) return; // 正在拖曳時不處理
const rect = th.getBoundingClientRect();
if (rect.right - e.clientX < 10) {
th.classList.add('resizing');
} else {
th.classList.remove('resizing');
}
});
// 滑鼠按下:準備拖曳
th.addEventListener('mousedown', e => {
const rect = th.getBoundingClientRect();
if (rect.right - e.clientX < 10) {
dragCell = th;
startX = e.clientX;
startWidth = th.offsetWidth;
th.classList.add('resizing');
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
}
});
});
// 全域滑鼠移動:執行寬度調整
document.addEventListener('mousemove', e => {
if (!dragCell) return;
const newWidth = startWidth + (e.clientX - startX);
if (newWidth > 20) { // 最小寬度保護
dragCell.style.width = newWidth + 'px';
// 同步調整同欄所有儲存格
const colIndex = dragCell.cellIndex;
table.querySelectorAll('tr').forEach(row => {
if (row.cells[colIndex]) {
row.cells[colIndex].style.width = newWidth + 'px';
}
});
}
});
// 滑鼠釋放:結束拖曳
document.addEventListener('mouseup', () => {
if (dragCell) {
dragCell.classList.remove('resizing');
dragCell = null;
document.body.style.cursor = '';
document.body.style.userSelect = '';
}
});
// 滑鼠離開視窗也要結束拖曳
document.addEventListener('mouseleave', () => {
if (dragCell) {
dragCell.classList.remove('resizing');
dragCell = null;
document.body.style.cursor = '';
document.body.style.userSelect = '';
}
});
</script>
</body>
</html>
document: mousemove/mouseup 綁在 document 上,確保滑鼠快速移出 th 區域仍能持續追蹤與正確釋放。cellIndex 同步欄寬: 每個 td/th 皆有 cellIndex 屬性表示欄索引,透過遍歷所有 tr 同步設定同欄儲存格寬度。col-resize 並禁用文字選取,提升操作手感。touchstart/touchmove/touchend 事件邏輯。--col-N-width)控制,僅更新變數值,瀏覽器自動重算佈局。table-layout: fixed 可獲得更穩定的欄寬渲染行為。這個元件可直接整合至後台管理系統、報表頁面,大幅提升使用者對大型表格的操作體驗。