• vue实现div拖拽


    首先,你需要在Vue组件中添加一个div元素,并设置它的样式为可拖拽:

    1. class="draggable" @mousedown="startDrag" @mouseup="stopDrag" @mousemove="drag">
  • 然后,在Vue组件的methods中添加以下方法:

    1. data() {
    2. return {
    3. dragging: false,
    4. x: 0,
    5. y: 0,
    6. startX: 0,
    7. startY: 0
    8. };
    9. },
    10. methods: {
    11. startDrag(event) {
    12. this.dragging = true;
    13. this.startX = event.clientX - this.x;
    14. this.startY = event.clientY - this.y;
    15. },
    16. stopDrag() {
    17. this.dragging = false;
    18. },
    19. drag(event) {
    20. if (this.dragging) {
    21. this.x = event.clientX - this.startX;
    22. this.y = event.clientY - this.startY;
    23. }
    24. }
    25. }

    最后,在CSS中添加以下样式

    1. .draggable {
    2. position: absolute;
    3. left: 0;
    4. top: 0;
    5. cursor: move;
    6. }

    移动端:

    对于移动端,需要使用触摸事件来实现拖拽功能。以下是在Vue 3中使用触摸事件实现移动端拖拽的代码示例:

    1. <script>
    2. export default {
    3. data() {
    4. return {
    5. dragging: false,
    6. x: 0,
    7. y: 0,
    8. startX: 0,
    9. startY: 0
    10. };
    11. },
    12. methods: {
    13. startDrag(event) {
    14. this.dragging = true;
    15. this.startX = event.touches[0].clientX - this.x;
    16. this.startY = event.touches[0].clientY - this.y;
    17. },
    18. stopDrag() {
    19. this.dragging = false;
    20. },
    21. drag(event) {
    22. if (this.dragging) {
    23. this.x = event.touches[0].clientX - this.startX;
    24. this.y = event.touches[0].clientY - this.startY;
    25. }
    26. }
    27. }
    28. };
    29. script>
    30. <style>
    31. .draggable {
    32. position: absolute;
    33. left: 0;
    34. top: 0;
    35. cursor: move;
    36. }
    37. style>

    在移动端,我们使用@touchstart、@touchend和@touchmove事件监听器来代替桌面端的鼠标事件。在startDrag和drag方法中,我们使用event.touches[0].clientX和event.touches[0].clientY来获取触摸点的位置。

    这样,你就可以在Vue 3中实现移动端的div拖拽功能了。

  • 相关阅读:
    JAVA URL请求
    WPF 截图控件之移除控件(九)「仿微信」
    数据结构:(c实现)手把手教你实现栈和队列(内附详细代码)
    使用docker搭建kafka集群、可视化操作台
    如何优雅部署OpenStack私有云II--异常处理记录
    RFM分析 | 一招搞定精细化客户管理,盒马鲜生等企业都在用
    Nginx网关配置
    你知道有哪些好用的数据分析工具类软件?
    ipvs之ipvs0网卡
    神经网络控制系统的应用,神经网络控制基本原理
  • 原文地址:https://blog.csdn.net/weixin_53841730/article/details/134017441