Newer
Older
Nanping_sponge_HHDP / src / directive / el-drag-div / index.js
@liyingjing liyingjing on 25 Oct 2023 881 bytes 海绵大屏
// v-divDrag: 弹窗拖拽属性

export default {
  // 指令的定义
  mounted: function (el, binding) {
    let oDiv = el; // 获取当前元素
    // 获取指令的值
    const ifDrag = binding.value;
    if (ifDrag) {
      oDiv.onmousedown = e => {
        //console.log("onmousedown");
        // 算出鼠标相对元素的位置
        let disX = e.clientX - oDiv.offsetLeft;
        let disY = e.clientY - oDiv.offsetTop;

        document.onmousemove = e => {
          // 用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
          let left = e.clientX - disX;
          let top = e.clientY - disY;

          oDiv.style.left = left + 'px';
          oDiv.style.top = top + 'px';
        };

        document.onmouseup = e => {
          document.onmousemove = null;
          document.onmouseup = null;
        };
      };
    }
  },
};