vue实现div拖拽

编程入门 行业动态 更新时间:2024-10-23 20:28:40

vue实现div<a href=https://www.elefans.com/category/jswz/34/1765858.html style=拖拽"/>

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拖拽

本文发布于:2023-12-03 20:36:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1657379.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:拖拽   vue   div

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!