拖拽"/>
vue实现div拖拽
首先,你需要在Vue组件中添加一个div元素,并设置它的样式为可拖拽:
<div class="draggable" @mousedown="startDrag" @mouseup="stopDrag" @mousemove="drag"><!-- 内容 -->
</div>
然后,在Vue组件的methods中添加以下方法:
data() {return {dragging: false,x: 0,y: 0,startX: 0,startY: 0};
},
methods: {startDrag(event) {this.dragging = true;this.startX = event.clientX - this.x;this.startY = event.clientY - this.y;},stopDrag() {this.dragging = false;},drag(event) {if (this.dragging) {this.x = event.clientX - this.startX;this.y = event.clientY - this.startY;}}
}
最后,在CSS中添加以下样式
.draggable {position: absolute;left: 0;top: 0;cursor: move;
}
移动端:
对于移动端,需要使用触摸事件来实现拖拽功能。以下是在Vue 3中使用触摸事件实现移动端拖拽的代码示例:
<template><div class="draggable" @touchstart="startDrag" @touchend="stopDrag" @touchmove="drag"><!-- 内容 --></div>
</template><script>
export default {data() {return {dragging: false,x: 0,y: 0,startX: 0,startY: 0};},methods: {startDrag(event) {this.dragging = true;this.startX = event.touches[0].clientX - this.x;this.startY = event.touches[0].clientY - this.y;},stopDrag() {this.dragging = false;},drag(event) {if (this.dragging) {this.x = event.touches[0].clientX - this.startX;this.y = event.touches[0].clientY - this.startY;}}}
};
</script><style>
.draggable {position: absolute;left: 0;top: 0;cursor: move;
}
</style>
在移动端,我们使用@touchstart、@touchend和@touchmove事件监听器来代替桌面端的鼠标事件。在startDrag和drag方法中,我们使用event.touches[0].clientX和event.touches[0].clientY来获取触摸点的位置。
这样,你就可以在Vue 3中实现移动端的div拖拽功能了。
更多推荐
vue实现div拖拽
发布评论