You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将jQuery实现的表格单元格范围选择功能转为原生JavaScript实现

原生JavaScript实现方案

以下代码完全替代原有jQuery版本,功能完全对齐,无任何第三方依赖:

1. HTML代码(可移除原有jQuery引用)

<body>
点击拖拽或按住shift键即可选中单元格。
<table id="table">
  <tr>
    <td></td><td></td><td></td><td></td>
  </tr>
  <tr>
    <td></td><td></td><td></td><td></td>
  </tr>
  <tr>
    <td></td><td></td><td></td><td></td>
  </tr>
  <tr>
    <td></td><td></td><td></td><td></td>
  </tr>
</table>
</body>

2. CSS代码(和原版本一致,可直接复用)

table td {
    border: 1px solid #999;
    width: 40px;
    height: 40px;
    margin: 10px;
    cursor: cell;
}
td.selected {
    background-color: green;
}

3. JavaScript代码

const table = document.getElementById('table');
let isMouseDown = false;
let startRowIndex = null;
let startCellIndex = null;

// 清除所有选中状态
function clearSelection() {
    document.querySelectorAll('#table td.selected').forEach(cell => {
        cell.classList.remove('selected');
    });
}

function selectTo(cell) {
    const row = cell.parentNode;
    const cellIndex = cell.cellIndex;
    const rowIndex = row.rowIndex;
    
    let rowStart = rowIndex < startRowIndex ? rowIndex : startRowIndex;
    let rowEnd = rowIndex < startRowIndex ? startRowIndex : rowIndex;
    let cellStart = cellIndex < startCellIndex ? cellIndex : startCellIndex;
    let cellEnd = cellIndex < startCellIndex ? startCellIndex : cellIndex;
    
    // 给范围内单元格加选中样式
    for (let i = rowStart; i <= rowEnd; i++) {
        const currentRow = table.rows[i];
        for (let j = cellStart; j <= cellEnd; j++) {
            currentRow.cells[j].classList.add('selected');
        }
    }
}

// 绑定单元格事件
table.querySelectorAll('td').forEach(cell => {
    cell.addEventListener('mousedown', e => {
        isMouseDown = true;
        clearSelection();
        if (e.shiftKey) {
            selectTo(cell);
        } else {
            cell.classList.add('selected');
            startCellIndex = cell.cellIndex;
            startRowIndex = cell.parentNode.rowIndex;
        }
        e.preventDefault(); // 阻止默认文本选中行为
    });

    cell.addEventListener('mouseover', () => {
        if (!isMouseDown) return;
        clearSelection();
        selectTo(cell);
    });

    cell.addEventListener('selectstart', e => {
        e.preventDefault();
    });
});

// 全局监听鼠标抬起结束选中状态
document.addEventListener('mouseup', () => {
    isMouseDown = false;
});

内容的提问来源于stack exchange,提问作者Muhammad Tayyab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 19:36:10