<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>mergecell test</title> <style> #tab { outline: none; } td { -moz-user-select: none; -webkit-user-select: none; user-select: none; width: 100px; height: 50px; } </style> </head> <body> <table width="100%" border="1" cellspacing="0" cellpadding="0" id="tab"> <tr> <td>张三 </td> <td>男 </td> <td>22 </td> <td>数学 </td> <td>90 </td> </tr> <tr> <td>张三 </td> <td>男 </td> <td>22 </td> <td>语文 </td> <td>70 </td> </tr> <tr> <td>张三 </td> <td>男 </td> <td>22 </td> <td>英语 </td> <td>60 </td> </tr> <tr> <td>李四 </td> <td>女 </td> <td>19 </td> <td>数学 </td> <td>60 </td> </tr> <tr> <td>李四 </td> <td>女 </td> <td>19 </td> <td>语文 </td> <td>60 </td> </tr> <tr> <td>王五 </td> <td>男 </td> <td>19 </td> <td>英语 </td> <td>60 </td> </tr> </table> <button onclick="merge()">合并</button> <script> const tab = document.querySelector('#tab') let start = null, end = null, flag = false, startEle = null, mergeText = '' tab.addEventListener('mousedown', e => { if (e.target.nodeName.toLowerCase() == 'td') { flag = true startEle = e.target start = find(e.target) } }) tab.addEventListener('mousemove', e => { if (e.target.nodeName.toLowerCase() == 'td' && flag) { let target = e.target target.style.borderColor = 'red' } }) tab.addEventListener('mouseup', e => { flag = false end = find(e.target) }) function find(target) { console.log(tab.rows) for (let i = 0; i < tab.rows.length; i++) { let row = tab.rows[i] for (let j = 0; j < row.cells.length; j++) { let cell = row.cells[j] if (cell == target) { return { row: i, col: j, } } } } } function setBorder() { } function merge() { console.log(start, end) let startRow = start.row <= end.row ? start.row : end.row, endRow = start.row >= end.row ? start.row : end.row, startCol = start.col <= end.col ? start.col : end.col, endCol = start.col >= end.col ? start.col : end.col for (let row = startRow; row <= endRow; row++) { for (let col = startCol; col <= endCol; col++) { let cell = tab.rows[row].cells[col] mergeText += cell.innerText if (cell !== startEle) cell.style.display = 'none' } } startEle.rowSpan += Math.abs(end.row - start.row) startEle.colSpan += Math.abs(end.col - start.col) startEle.innerText = mergeText start = null end = null startEle = null mergeText = '' } </script> </body> </html>