td
單元格內,有未知層dom
結構
<style>.highlight {background-color: yellow;}
</style>
<table id="myTable"><colgroup><col style="background-color: lightblue;"><col style="background-color: lightgreen;"></colgroup><tbody><tr><td>單元格 1</td><td>單元格 2</td></tr><tr><td>單元格 3</td><td>單元格 4</td></tr></tbody>
</table>
監聽用戶框選單元格的行為
const table = document.querySelector('#detil-tbale .ant-table .ant-table-scroll .ant-table-body table.ant-table-fixed',
);
const cells = table.getElementsByTagName('td');
let isMouseDown = false;
let startCell, endCell;
// 鼠標按下事件監聽
table.addEventListener('mousedown', function (e) {isMouseDown = true;startCell = e.target;endCell = e.target;selectCells();
});
// 鼠標移動事件監聽
table.addEventListener('mousemove', function (e) {if (!isMouseDown) return;endCell = e.target;selectCells();
});
// 鼠標釋放事件監聽
table.addEventListener('mouseup', function () {isMouseDown = false;
});
// 框選和著色函數
function selectCells() {// 清除所有單元格的 highlight 類for (let cell of cells) {cell.classList.remove('highlight');}// 確定選區范圍let [startRow, startCol] = getCellIndex(startCell);let [endRow, endCol] = getCellIndex(endCell);// 確定起始和結束行、列let minRow = Math.min(startRow, endRow);let maxRow = Math.max(startRow, endRow);let minCol = startCol; // 只選擇起始列let maxCol = startCol; // 只選擇起始列// 遍歷選區內的單元格并著色for (let row = minRow; row <= maxRow; row++) {let cell = table.rows[row].cells[minCol];cell.classList.add('highlight');}
}
// 輔助函數:獲取單元格的行列索引
function getCellIndex(cell) {const td = findRootElement(cell)const tr = td.parentNodeconsole.log(columns[td.cellIndex],'safasfasafs');return [tr.rowIndex, td.cellIndex];
}
function findRootElement(element) {if(element.tagName === 'TD') return elementif(element.parentElement.tagName === 'TD') return element.parentElementwhile (element.parentElement.tagName !== 'TD') {element = element.parentElement;}return element.parentElement
}