如果是div,
<template>
<div class="draggable"
@mousedown="startDrag"
style=" position: absolute;" :src="srcdata" controls="controls" width="480px" height="480px" autoplay="autoplay">
</div>
</div>
</template>
如果是视频video
<template>
<video class="draggable"
@mousedown="startDrag"
style=" position: absolute;left:30%;" :src="srcdata" controls="controls" width="480px" height="480px" autoplay="autoplay"></video>
</div>
</template>
data() {
return {
startX: 0,
startY: 0,
dragging: false,
}
}
methods: {
startDrag(e) {
// 记录初始位置和设置拖动标识
this.startX = e.clientX - e.target.offsetLeft;
this.startY = e.clientY - e.target.offsetTop;
this.dragging = true;
// 绑定mousemove和mouseup事件
window.addEventListener('mousemove', this.drag);
window.addEventListener('mouseup', this.stopDrag);
},
drag(e) {
if (!this.dragging) return;
// 计算新位置
const x = e.clientX - this.startX;
const y = e.clientY - this.startY;
// 更新div的位置
e.target.style.left = `${x}px`;
e.target.style.top = `${y}px`;
},
stopDrag() {
this.dragging = false;
// 移除事件监听
window.removeEventListener('mousemove', this.drag);
window.removeEventListener('mouseup', this.stopDrag);
},
}
<style>
.draggable {
cursor: move;
}
</style>