vue3自定义拖拽指令

发布于:2024-05-16 ⋅ 阅读:(23) ⋅ 点赞:(0)

自定义拖拽指令: 鼠标位置相对于当前文档的x坐标 - 鼠标位置相对于当前物体的x坐标 就是 物体在文档中的位置


<script setup>
const vMove = {
  mounted(el) {
    let x, y;
    el.addEventListener("mousedown", elMounseDown);
    function elMounseDown(e) {
      console.log("pagex:", e.pageX, "pagey:", e.pageY);
      x = pageOffset(e).x - parseInt(getStyles(this, 'left'));
      y = pageOffset(e).y - parseInt(getStyles(this, 'top'));
      const elMouseMove = (e) => {
        el.style.left = pageOffset(e).x - x + "px";
        el.style.top = pageOffset(e).y - y + "px";
      };
      document.addEventListener("mousemove", elMouseMove);
      document.addEventListener("mouseup", () => {
        document.removeEventListener("mousemove", elMouseMove);
      });
    }
  }
};
function pageOffset(e) {
  //    获取滚动条的距离
  var sLeft = getScrollOffset().x,
    sTop = getScrollOffset().y,
    //      获取文档的偏移距离,有可能不存在为undefined
    dShiftTop = document.documentElement.clientTop || 0,
    dShiftLeft = document.documentElement.clientLeft || 0;
  return {
    x: e.clientX + sLeft - dShiftLeft,
    y: e.clientY + sTop - dShiftTop,
  };
}
function getScrollOffset() {
  if (window.pageXOffset) {
    //w3c标准
    return {
      x: window.pageXOffset,
      y: window.pageYOffset,
    };
  } else {
    return {
      x: document.documentElement.scrollLeft + document.body.scrollLeft,
      y: document.documentElement.scrollTop + document.body.scrollTop,
    };
  }
}
function getStyles(ele, attr) {
  if (window.getComputedStyle) {
    if (attr) {
      return window.getComputedStyle(ele, null)[attr];
    } else {
      return window.getComputedStyle(ele, null);
    }
  } else if (ele.currentStyle) {
    if (attr) {
      ele.currentStyle[attr];
    } else {
      ele.currentStyle;
    }
  }
}
</script>

<template>
  <div
    class="move-box"
    v-move
  >
  </div>
</template>

<style scoped>
.move-box {
  position: relative;
  top: 0;
  left: 30px;
  width: 200px;
  height: 200px;
  background-color: #646cffaa;
}
</style>