基本能实现拖动,拖动之后显示高亮
html语言
<el-table
:data="file_list
style="width: 100%;height: 700px;"
row-key="id"
ref="table"
:row-class-name="rowClassName"
@mousedown.native="handleMouseDown"
@mouseup.native="handleMouseUp"
>
<el-table-column
prop="name"
label="文件名称"
width="auto">
</el-table-column>
</el-table>
js
var app = new Vue({
el: "#app",
data() {
return{
// 新增变量用于存储当前高亮行的引用
currentHoverRow: null,
pressTimer: null,
rowHeight: 50,
isLongPress: false,
longPressTimer: null,
releasePosition: { x: 0, y: 0 },
drop:{
dropId:'',
floderId:''
},//新旧文件夹id
file_list:[]
},
methods:{
getRowHeight() {
const table = this.$refs.table.$el.querySelector('.el-table__body-wrapper');
const firstRow = table.querySelector('.el-table__body tr');
if (firstRow) {
this.rowHeight = firstRow.getBoundingClientRect().height;
console.log('每行的高度:', this.rowHeight);
}
},
handleMouseDown() {
this.longPressTimer = setTimeout(() => {
// 长按逻辑
}, 1000); // 设置长按时间阈值,单位为毫秒
},
handleMouseUp() {
clearTimeout(this.longPressTimer);
// 获取鼠标释放时所在的行位置
const table = this.$refs.table.$el.querySelector('.el-table__body-wrapper');
const rect = table.getBoundingClientRect();
const mouseY = event.clientY - rect.top;
const rowIndex = Math.floor(mouseY / this.rowHeight);
// 获取该行数据并打印
this.selectedRow = this.file_list[rowIndex];
this.drop.floderId=this.selectedRow.id;
console.log('鼠标释放时所在行的数据:', this.selectedRow);
},
handleRowClick(row, column, event) {
// 打印行数据
console.log(row);
},
endLongPress(event) {
this.releasePosition.x = event.clientX;
this.releasePosition.y = event.clientY;
console.log('鼠标释放位置:', this.releasePosition);
this.handleMouseUp()
},
// 行的className回调方法,为表格的每一行添加一个className
rowClassName(row) {
return `row-class-${row.row.id}`;
},
//拖动事件
rowDrag() {
this.$nextTick(() => {
this.file_list.map(v => {
let dom = document.getElementsByClassName(`row-class-${v.id}`)[0];
if(dom) {
dom.setAttribute('draggable', true);
// 添加 dragstart 事件监听器
dom.addEventListener("dragstart", function(ev) {
// ... 其他逻辑
});
// 添加 drag 事件监听器
dom.addEventListener("drag", (ev) => {
const tableBody = this.$refs.table.$el.querySelector('.el-table__body-wrapper tbody');
const rows = tableBody.querySelectorAll('.el-table__row');
rows.forEach((row, rowIndex) => {
const rowRect = row.getBoundingClientRect();
// 判断鼠标是否在当前行内
if (
ev.clientX >= rowRect.left &&
ev.clientX <= rowRect.right &&
ev.clientY >= rowRect.top &&
ev.clientY <= rowRect.bottom
) {
// 如果当前鼠标所在行与已高亮行不同,则移除旧的高亮并添加新的高亮
if (this.currentHoverRow && this.currentHoverRow !== row) {
this.currentHoverRow.classList.remove('selected-row');
}
//0为文件夹,1为文件
if(app.file_list[row.sectionRowIndex].file_type!==1){
row.classList.add('selected-row');
}
this.currentHoverRow = row;
} else if (this.currentHoverRow === row) {
// 鼠标离开了先前高亮的行,移除高亮
row.classList.remove('selected-row');
this.currentHoverRow = null;
}
});
});
dom.addEventListener("dragend", app.endLongPress);
}
})
});
},},
mounted() {
this.rowDrag();
this.getRowHeight();
}