# 可拖动区域

原理:区域绝对定位,拖动过程中修改区域定位样式

<template>
  <div class="box">
    <div
      class="drag-div"
      :style="{top,left}"
      @mousedown="mousedown"
      @mouseup="mouseup"
      @mouseleave="mouseleave"
      @mousemove="mousemove"
    ></div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        top: "0",
        left: "0",
        moving: false,
      };
    },
    methods: {
      mousedown() {
        this.moving = true;
      },
      mouseup() {
        this.moving = false;
      },
      mouseleave() {
        this.moving = false;
      },
      mousemove(e) {
        if (this.moving) {
          this.top = Number(this.top.replace("px", "")) + e.movementY + "px";
          this.left = Number(this.left.replace("px", "")) + e.movementX + "px";
        }
      },
    },
  };
</script>
<style>
  .box {
    width: 200px;
    height: 200px;
    background: lightgreen;
    position: relative;
  }

  .drag-div {
    width: 50px;
    height: 50px;
    background: red;
    position: absolute;
  }
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
Expand Copy