• 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拖拽功能了。

  • 相关阅读:
    【Python大数据笔记_day05_Hive基础操作】
    jpg格式图片怎么弄?不同格式图片该怎么转换?
    数字孪生|数字孪生装备-关键技术和发展阶段
    springboot2 --- 基础入门
    FPGA的主流技术与市场表现方面的调研报告
    python无法import相对路径中的包?一次说清楚python的import机制~
    Java审计框架基础
    05【DAO开发的方式】
    @slf4j 找不到log
    前端面试题集锦(2)
  • 原文地址:https://blog.csdn.net/weixin_53841730/article/details/134017441