简单实现一个具有“框选”、“复制”、“粘贴”功能的表格
首先,展示HTML代码:
<template>
<div class="tableContainer">
<div id="table_head" class="table_head">
<table>
<thead>
<tr>
<th :style="{'min-width':colWidth+'px','width':colWidth+'px',height:rowHeight+'px'}" class="fixed-th">Column 1</th>
<th class="cell-td">Column 2</th>
<th class="cell-td">Column 3</th>
<th class="cell-td">Column 4</th>
<th class="cell-td">Column 5</th>
</tr>
</thead>
</table>
</div>
<table id="excelTable">
<tbody>
<tr v-for="(item,index) in tableData" :key="index" @mousedown="mousedownHandle(index,$event)" @mousemove="mousemoveHandle(index,$event)">
<td id="fixedCell" aria-details="0" :style="{'min-width':colWidth+'px','width':colWidth+'px',height:rowHeight+'px'}" class="fiexed-td">{{ item.tdOne }}</td>
<td aria-details="1" class="cell-td">{{ item.tdTwo }}</td>
<td aria-details="2" class="cell-td">{{ item.tdThress }}</td>
<td aria-details="3" class="cell-td">{{ item.tdFour }}</td>
<td aria-details="4" class="cell-td">{{ item.tdFive }}</td>
</tr>
</tbody>
</table>
<div class="borderCover" :style="{'position': 'absolute','left':left+'px','top':top+'px',width:width+'px','height':height+'px'}" />
</div>
</template>
然后,JavaScript代码:
<script>
import NP from 'number-precision'
import Sortable from 'sortablejs'
export default {
name: 'EasyTable',
props: {
rowHeight: {
type: Number,
default: () => 36
},
colWidth: {
type: Number,
default: () => 120
}
},
data() {
return {
tableData: [
{
tdOne: 'Row 1, Cell 1',
tdTwo: 'Row 1, Cell 2',
tdThress: 'Row 1, Cell 3',
tdFour: 'Row 1, Cell 4',
tdFive: 'Row 1, Cell 5'
},
{
tdOne: 'Row 2, Cell 1',
tdTwo: 'Row 2, Cell 2',
tdThress: 'Row 2, Cell 3',
tdFour: 'Row 1, Cell 4',
tdFive: 'Row 1, Cell 5'
},
{
tdOne: 'Row 3, Cell 1',
tdTwo: 'Row 3, Cell 2',
tdThress: 'Row 3, Cell 3',
tdFour: 'Row 1, Cell 4',
tdFive: 'Row 1, Cell 5'
},
{
tdOne: 'Row 3, Cell 1',
tdTwo: 'Row 3, Cell 2',
tdThress: 'Row 3, Cell 3',
tdFour: 'Row 1, Cell 4',
tdFive: 'Row 1, Cell 5'
},
{
tdOne: 'Row 3, Cell 1',
tdTwo: 'Row 3, Cell 2',
tdThress: 'Row 3, Cell 3',
tdFour: 'Row 1, Cell 4',
tdFive: 'Row 1, Cell 5'
},
{
tdOne: 'Row 3, Cell 1',
tdTwo: 'Row 3, Cell 2',
tdThress: 'Row 3, Cell 3',
tdFour: 'Row 1, Cell 4',
tdFive: 'Row 1, Cell 5'
},
{
tdOne: 'Row 3, Cell 1',
tdTwo: 'Row 3, Cell 2',
tdThress: 'Row 3, Cell 3',
tdFour: 'Row 1, Cell 4',
tdFive: 'Row 1, Cell 5'
},
{
tdOne: 'Row 3, Cell 1',
tdTwo: 'Row 3, Cell 2',
tdThress: 'Row 3, Cell 3',
tdFour: 'Row 1, Cell 4',
tdFive: 'Row 1, Cell 5'
},
{
tdOne: 'Row 3, Cell 1',
tdTwo: 'Row 3, Cell 2',
tdThress: 'Row 3, Cell 3',
tdFour: 'Row 1, Cell 4',
tdFive: 'Row 1, Cell 5'
},
{
tdOne: 'Row 3, Cell 1',
tdTwo: 'Row 3, Cell 2',
tdThress: 'Row 3, Cell 3',
tdFour: 'Row 1, Cell 4',
tdFive: 'Row 1, Cell 5'
},
{
tdOne: 'Row 3, Cell 1',
tdTwo: 'Row 3, Cell 2',
tdThress: 'Row 3, Cell 3',
tdFour: 'Row 1, Cell 4',
tdFive: 'Row 1, Cell 5'
},
{
tdOne: 'Row 3, Cell 1',
tdTwo: 'Row 3, Cell 2',
tdThress: 'Row 3, Cell 3',
tdFour: 'Row 1, Cell 4',
tdFive: 'Row 1, Cell 5'
},
{
tdOne: 'Row 3, Cell 1',
tdTwo: 'Row 3, Cell 2',
tdThress: 'Row 3, Cell 3',
tdFour: 'Row 1, Cell 4',
tdFive: 'Row 1, Cell 5'
},
{
tdOne: 'Row 3, Cell 1',
tdTwo: 'Row 3, Cell 2',
tdThress: 'Row 3, Cell 3',
tdFour: 'Row 1, Cell 4',
tdFive: 'Row 1, Cell 5'
},
{
tdOne: 'Row 3, Cell 1',
tdTwo: 'Row 3, Cell 2',
tdThress: 'Row 3, Cell 3',
tdFour: 'Row 1, Cell 4',
tdFive: 'Row 1, Cell 5'
},
{
tdOne: 'Row 3, Cell 1',
tdTwo: 'Row 3, Cell 2',
tdThress: 'Row 3, Cell 3',
tdFour: 'Row 1, Cell 4',
tdFive: 'Row 1, Cell 5'
},
{
tdOne: 'Row 3, Cell 1',
tdTwo: 'Row 3, Cell 2',
tdThress: 'Row 3, Cell 3',
tdFour: 'Row 1, Cell 4',
tdFive: 'Row 1, Cell 5'
},
{
tdOne: 'Row 3, Cell 1',
tdTwo: 'Row 3, Cell 2',
tdThress: 'Row 3, Cell 3',
tdFour: 'Row 1, Cell 4',
tdFive: 'Row 1, Cell 5'
},
{
tdOne: 'Row 3, Cell 1',
tdTwo: 'Row 3, Cell 2',
tdThress: 'Row 3, Cell 3',
tdFour: 'Row 1, Cell 4',
tdFive: 'Row 1, Cell 5'
},
{
tdOne: 'Row 3, Cell 1',
tdTwo: 'Row 3, Cell 2',
tdThress: 'Row 3, Cell 3',
tdFour: 'Row 1, Cell 4',
tdFive: 'Row 1, Cell 5'
}
],
isMouseDown: false,
startCell: {
rowIndex: null,
columnIndex: null,
x: null,
y: null
},
endCell: {
rowIndex: null,
columnIndex: null,
x: null,
y: null
},
c_width: this.colWidth, // 单元格宽度
fixedNum: 0, // 列固定宽度的列数
// 框选框
left: null,
top: null,
width: null,
height: null,
// 滚动条
scrollTimeout: null,
scrollInterval: null,
tableContainerEle: null, // 表格容器
browserWidth: null, // 表格容器的宽度
browserLeft: null, // 表格容器 距离浏览器左侧距离
thead_Height: null, // 表格头部的高度
scrollStep: 10, // 滚动步长
scrollDelay: 100, // 滚动延迟时长
// 复制粘贴
isCopy: false,
copyContent: []
}
},
mounted() {
document.addEventListener('mouseup', this.mouseupHandle)
document.addEventListener('keydown', this.handleKeyDown)
this.$nextTick(() => {
const thead_dom = document.getElementById('table_head')
const fixedNum = thead_dom.querySelectorAll('th.fixed-th').length
const cell_dom = document.getElementsByClassName('cell-td')[0]
this.tableContainerEle = document.getElementsByClassName('tableContainer')[0]
const { width, left } = this.tableContainerEle.getBoundingClientRect()
this.browserWidth = width
this.browserLeft = left
this.thead_Height = thead_dom.clientHeight
this.c_width = cell_dom.clientWidth
this.fixedNum = fixedNum// 列宽度固定的个数
this.sortRowHandle()
})
},
beforeDestroy() {
document.removeEventListener('mouseup', this.mouseupHandle)
document.removeEventListener('keydown', this.handleKeyDown)
clearInterval(this.scrollInterval)
this.scrollInterval = null
clearTimeout(this.scrollTimeout)
this.scrollTimeout = null
},
methods: {
// 排序
sortRowHandle() {
const table = document.getElementById('excelTable')
const tbody = table.getElementsByTagName('tbody')[0]
const sortableInit = Sortable.create(tbody, {
animation: 150,
ghostClass: 'blue-background-class',
sort: true,
onEnd: ({ newIndex, oldIndex }) => {
console.log(newIndex, oldIndex)
}
})
console.log(sortableInit.destroy())
},
handleKeyDown(event) {
// Ctrl+c
if (event.ctrlKey && (event.keyCode === 67 || event.key === 'c')) {
this.copy()
}
// Ctrl+v
if (event.ctrlKey && (event.keyCode === 86 || event.key === 'v')) {
this.paste()
}
},
// 复制
copy() {
if (this.startCell.columnIndex === null || !this.startCell.rowIndex === null) {
return
}
// 使用解构赋值直接获取坐标
const { columnIndex: s_columnIndex, rowIndex: s_rowIndex } = this.startCell
const { columnIndex: e_columnIndex, rowIndex: e_rowIndex } = this.endCell
this.copyContent = []
// 获取 复制 内容
this.copyContent = Array.from({ length: e_rowIndex - s_rowIndex + 1 }, (_, rowIndex) =>
Array.from({ length: e_columnIndex - s_columnIndex + 1 }, (_, colIndex) =>
this.tableData[rowIndex + s_rowIndex][Object.keys(this.tableData[rowIndex + s_rowIndex])[colIndex + s_columnIndex]]
)
)
// this.tableData.forEach((item, _rowIndex) => {
// if (_rowIndex >= s_rowIndex && _rowIndex <= e_rowIndex) {
// const rowArr = []
// const column = item
// Object.keys(column).forEach((key, columnIndex) => {
// if (columnIndex >= s_columnIndex && columnIndex <= e_columnIndex) {
// rowArr.push(column[key])
// }
// })
// this.copyContent.push(rowArr)
// }
// })
this.isCopy = true
console.log(this.copyContent)
},
// 粘贴
paste() {
if (!this.isCopy || this.copyContent.length <= 0) {
return
}
const { columnIndex: s_columnIndex, rowIndex: s_rowIndex } = this.startCell
const { columnIndex: e_columnIndex, rowIndex: e_rowIndex } = this.endCell
// 计算复制区域的行数和列数
const copyRows = this.copyContent.length
const copyCols = this.copyContent[0].length || '+' // 防止copyContent为空数组或空项
// 确保粘贴区域不会超出tableData的边界
const validRowCount = Math.min(e_rowIndex - s_rowIndex + 1, copyRows)
const validColCount = Math.min(e_columnIndex - s_columnIndex + 1, copyCols)
for (let rowIndex = 0; rowIndex < validRowCount; rowIndex++) {
for (let colIndex = 0; colIndex < validColCount; colIndex++) {
// 获取复制内容中对应位置的值
const pasteValue = this.copyContent[rowIndex][colIndex]
// 更新tableData中的值
this.tableData[s_rowIndex + rowIndex][Object.keys(this.tableData[s_rowIndex + rowIndex])[s_columnIndex + colIndex]] = pasteValue
}
}
// this.tableData.forEach((item, _rowIndex) => {
// if (_rowIndex >= s_rowIndex && _rowIndex <= e_rowIndex) {
// const column = item
// const whichRow = _rowIndex - s_rowIndex
// const copyList = this.copyContent.length
// const double_row = parseInt(whichRow / copyList)
// const row_index = whichRow - (copyList * double_row)
// Object.keys(column).forEach((key, columnIndex) => {
// if (columnIndex >= s_columnIndex && columnIndex <= e_columnIndex) {
// const whichColumn = columnIndex - s_columnIndex
// if (this.copyContent.length === 1 && this.copyContent[0].length === 1) {
// column[key] = this.copyContent[0][0]
// return
// }
// if (this.copyContent[row_index][whichColumn]) {
// column[key] = this.copyContent[row_index][whichColumn]
// }
// }
// })
// }
// })
},
mousedownHandle(rowIndex, e) {
if (e.target.tagName === 'TD' && e.target.id !== 'fixedCell') {
this.isMouseDown = true
const columnIndex = parseInt(e.target.getAttribute('aria-details'), 10)
const cellX = NP.times((columnIndex - this.fixedNum), this.c_width) + NP.times(this.fixedNum, this.colWidth)
const cellY = NP.times(rowIndex, this.rowHeight)
this.startCell = {
rowIndex: rowIndex * 1,
columnIndex,
x: cellX,
y: cellY
}
this.endCell = { ...this.startCell }
this.updateSelectionRect()
}
},
mousemoveHandle(rowIndex, e) {
if (this.isMouseDown && e.target.id !== 'fixedCell') {
const element = e.target
const columnIndex = element.getAttribute('aria-details')
if (columnIndex === this.endCell.columnIndex && rowIndex === this.endCell.rowIndex) {
return
}
this.endCell.rowIndex = rowIndex * 1
this.endCell.columnIndex = columnIndex * 1
this.endCell.x = NP.times(columnIndex, this.c_width)
this.endCell.y = NP.times(rowIndex, this.rowHeight) + this.rowHeight
this.updateSelectionRect()
this.scrollMove(e.clientX)
}
},
updateSelectionRect() {
// const s_columnIndex = this.startCell.columnIndex// 开始位置--第几行
// const s_rowIndex = this.startCell.rowIndex// 开始位置--第几列
// const e_columnIndex = this.endCell.columnIndex// 结束位置--第几行
// const e_rowIndex = this.endCell.rowIndex// 结束位置--第几列
const { startIndex, endIndex } = this.getMinMaxIndices()
this.left = NP.times((startIndex.columnIndex - this.fixedNum), this.c_width) + NP.times(this.fixedNum, this.colWidth)
this.width = (endIndex.columnIndex - startIndex.columnIndex + 1) * this.c_width
this.top = NP.plus(NP.times(startIndex.rowIndex, this.rowHeight), this.thead_Height)
this.height = NP.times((endIndex.rowIndex - startIndex.rowIndex + 1), this.rowHeight)
// if (e_columnIndex - s_columnIndex < 0) { // 说明结束位置---在开始位置左侧
// this.left = this.endCell.x
// this.width = (s_columnIndex - e_columnIndex) * 511 + 511
// } else {
// this.left = this.startCell.x
// this.width = (e_columnIndex - s_columnIndex) * 511 + 511
// }
// if (e_rowIndex - s_rowIndex < 0) { // 说明结束位置---在开始位置上方
// this.top = this.endCell.y
// this.height = (s_rowIndex - e_rowIndex) * 36 + 36
// } else {
// this.top = this.startCell.y
// this.height = (e_rowIndex - s_rowIndex) * 36 + 36
// }
},
getMinMaxIndices() {
const startIndex = {
rowIndex: Math.min(this.startCell.rowIndex, this.endCell.rowIndex),
columnIndex: Math.min(this.startCell.columnIndex, this.endCell.columnIndex)
}
const endIndex = {
rowIndex: Math.max(this.startCell.rowIndex, this.endCell.rowIndex),
columnIndex: Math.max(this.startCell.columnIndex, this.endCell.columnIndex)
}
return { startIndex, endIndex }
},
mouseupHandle() {
this.isMouseDown = false
clearTimeout(this.scrollTimeout)
this.scrollTimeout = null
clearInterval(this.scrollInterval)
this.scrollInterval = null
},
scrollMove(screenX) {
// if ((screenX - this.browserLeft) >= this.browserWidth - 20) {
// if (!this.scrollInterval) {
// this.scrollInterval = setInterval(() => {
// const tableContent_ele = this.tableContainerEle
// const scrollLeft = tableContent_ele.scrollLeft
// const scrollWidth = tableContent_ele.scrollWidth
// const clientWidth = tableContent_ele.clientWidth
// if (scrollLeft < scrollWidth - clientWidth) {
// tableContent_ele.scrollLeft = scrollLeft + this.scrollStep
// } else {
// clearInterval(this.scrollInterval)
// this.scrollInterval = null
// }
// }, 100)
// }
// return
// }
// if ((screenX - this.browserLeft) <= 0) {
// if (!this.scrollInterval) {
// this.scrollInterval = setInterval(() => {
// const tableContent_ele = document.getElementsByClassName('tableContainer')[0]
// const scrollLeft = tableContent_ele.scrollLeft
// console.log(scrollLeft)
// if (scrollLeft > 0) {
// tableContent_ele.scrollLeft = scrollLeft - this.scrollStep
// } else {
// clearInterval(this.scrollInterval)
// this.scrollInterval = null
// }
// }, 100)
// }
// return
// }
clearInterval(this.scrollInterval)
this.scrollInterval = null
// 判断是否需要滚动
const scrollDirection = (screenX - this.browserLeft) > (this.browserWidth - 50) ? 1 : (screenX - this.browserLeft) <= 50 ? -1 : 0
if (scrollDirection) {
this.scrollInterval = requestAnimationFrame(this.animateScroll.bind(this, scrollDirection))
} else {
clearTimeout(this.scrollTimeout)
this.scrollTimeout = null
this.scrollInterval = null
}
},
animateScroll(direction) {
clearTimeout(this.scrollTimeout)// 清除可能存在的旧延时调用
this.scrollTimeout = null
const tableContentEle = this.tableContainerEle
const scrollLeft = tableContentEle.scrollLeft
const scrollWidth = tableContentEle.scrollWidth
const clientWidth = tableContentEle.clientWidth
let newScrollLeft = scrollLeft
if (direction === 1 && scrollLeft < scrollWidth - clientWidth) {
newScrollLeft += this.scrollStep
} else if (direction === -1 && scrollLeft > 0) {
newScrollLeft -= this.scrollStep
}
// 更新滚动位置
tableContentEle.scrollLeft = newScrollLeft
// 如果还没有到达边界,继续滚动
if (newScrollLeft !== scrollLeft) {
this.scrollTimeout = setTimeout(() => {
this.animateScroll(direction)
}, this.scrollDelay)
} else {
clearTimeout(this.scrollTimeout)
this.scrollInterval = null
}
}
}
}
</script>
最后,展示CSS代码:
<style lang="less" scoped>
.tableContainer{
position: relative;
overflow-x: auto;
overflow-y: auto;
width: 100%;
height: 100%;
z-index: 100;
}
.table_head{
position: sticky;
top: 0;
z-index: 4;
}
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
cursor: pointer;
user-select: none; /* Standard property */
}
th {
background-color: #f2f2f2;
}
td.selected {
background-color: lightblue;
}
.fixed-th{
position: sticky;
left:0;
}
.fiexed-td{
position: sticky;
left:0;
background-color: #fff;
}
.borderCover{
position: absolute;
left: 0px;
top:0px;
z-index: -1;
border-top: 2px solid green;
border-right: 1px solid green;
border-bottom:1px solid green;
border-left:2px solid green;
background-color: rgba(76, 175, 80, 0.1);
}
</style>
总结:由于,网上handsontable第三方库,与sortable.js很难搭配使用,故手写一套 复制粘贴的表格;需要拖拽排序,需要注释掉console.log(sortableInit.destroy())这块代码,如有问题,请联系我,不吝赐教。最后文章原创,如有雷同,必究责任。
![在这里插入图片描述]