前端合并单元格拖拽代码
时间: 2023-03-19 19:25:25 浏览: 217
以下是一个前端合并单元格拖拽的代码示例:
HTML 代码:
```html
<table>
<thead>
<tr>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="2">小明</td>
<td>男</td>
<td>20</td>
</tr>
<tr>
<td>男</td>
<td>21</td>
</tr>
<tr>
<td>小红</td>
<td>女</td>
<td>22</td>
</tr>
</tbody>
</table>
```
CSS 代码:
```css
table {
border-collapse: collapse;
}
th,
td {
border: 1px solid black;
padding: 5px;
}
td.dragging {
opacity: 0.5;
}
```
JavaScript 代码:
```js
const tdList = document.getElementsByTagName('td')
let dragging = false
let dragStartIndex = -1
for (let i = 0; i < tdList.length; i++) {
const td = tdList[i]
td.addEventListener('mousedown', function (event) {
if (event.button === 0) {
dragging = true
dragStartIndex = i
td.classList.add('dragging')
}
})
td.addEventListener('mousemove', function () {
if (dragging) {
const dragEndIndex = i
const [startIndex, endIndex] = [Math.min(dragStartIndex, dragEndIndex), Math.max(dragStartIndex, dragEndIndex)]
const rows = []
for (let j = startIndex; j <= endIndex; j++) {
const row = tdList[j].parentNode
rows.push(row)
}
rows[0].cells[0].rowSpan = rows.length
for (let j = 1; j < rows.length; j++) {
rows[j].removeChild(rows[j].cells[0])
}
dragging = false
dragStartIndex = -1
td.classList.remove('dragging')
}
})
td.addEventListener('mouseup', function () {
dragging = false
dragStartIndex = -1
td.classList.remove('dragging')
})
td.addEventListener('mouseleave', function () {
dragging = false
dragStartIndex = -1
td.classList.remove('dragging')
})
}
```
这段代码可以实现在表格中拖拽合并单元格的功能。用户可以在表格中按住鼠标左键并拖动,选中需要合并的单元格范围,松开鼠标左键后,选中的单元格会被合并。
阅读全文