元素在可视区域内拖动,不超出可视区域 Vue

999 阅读1分钟

我是个程序猿,一天我坐在路边一边喝水一边苦苦检查bug。这时一个乞丐在我边上坐下了,开始要饭,我觉得可怜,就给了他1块钱,然后接着调试程序。他可能生意不好,就无聊的看看我在干什么,然后过了一会,他幽幽的说,这里少了个分号。。。分号。。。分号。。。 image-20220228103417433.png id6u3-ru5eo.gif

<template>
  <div>
    <!-- 鼠标点击拖动 -->
    <div ref="dragDiv" class="drag-div" @mousedown="handleMousedown"></div>
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },

  methods: {
    handleMousedown(e) {
      let dragDiv = this.$refs.dragDiv;
      // 获取浏览器窗口文档显示区域的宽度和高度,不包括滚动条。
      const { clientWidth, clientHeight } = document.documentElement;
      // 获取鼠标相对于当前元素的位置
      const disX = e.clientX - dragDiv.offsetLeft;
      const disY = e.clientY - dragDiv.offsetTop;
      // 鼠标点击不释放 进行拖动
      document.onmousemove = e => {
        //鼠标位置减去鼠标相对于当前元素的位置 获取此时此刻元素应该处于的位置
        let left = e.clientX - disX;
        let top = e.clientY - disY;
        // 获取元素的宽高
        const { offsetWidth, offsetHeight } = dragDiv;
        // 设置当前元素的位置 不能超出可视区域
        if (left < 0) {
          left = 0;
        }
        if (left > clientWidth - offsetWidth) {
          left = clientWidth - offsetWidth;
        }
        if (top < 0) {
          top = 0;
        }
        if (top > clientHeight - offsetHeight) {
          top = clientHeight - offsetHeight;
        }
        dragDiv.style.left = left + "px";
        dragDiv.style.top = top + "px";

      };

      // 鼠标点击释放 拖动结束
      document.onmouseup = () => {
        document.onmousemove = null;
      };
    }
  }
};
</script>

<style>
.drag-div {
  left: 50px;
  width: 200px;
  height: 200px;
  background: #ddd;
  position: fixed;
}

</style>