萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 實作表格欄寬可拖曳調整:完整可複製範例

功能說明

  • 滑鼠移至表頭單元格右邊緣(最後 10px)顯示 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>

核心實作細節

  1. 事件委派於 document: mousemove/mouseup 綁在 document 上,確保滑鼠快速移出 th 區域仍能持續追蹤與正確釋放。
  2. cellIndex 同步欄寬: 每個 td/th 皆有 cellIndex 屬性表示欄索引,透過遍歷所有 tr 同步設定同欄儲存格寬度。
  3. 最小寬度保護: 防止拖曳至負值或過窄導致版面崩壞。
  4. 游標與選取控制: 拖曳期間強制全域游標為 col-resize 並禁用文字選取,提升操作手感。

相容性與優化

  • 純原生 JS,無相依套件,IE10+、所有現代瀏覽器支援。
  • 若需支援觸控裝置,可補充 touchstart/touchmove/touchend 事件邏輯。
  • 大量資料列(>1000 列)時,同步設定寬度可能造成卡頓,可改用 CSS 變數(--col-N-width)控制,僅更新變數值,瀏覽器自動重算佈局。
  • 搭配 table-layout: fixed 可獲得更穩定的欄寬渲染行為。

這個元件可直接整合至後台管理系統、報表頁面,大幅提升使用者對大型表格的操作體驗。

copyright © 萬盛學電腦網 all rights reserved