vue中div的拖拽

<template>
  <div>
    <div class="crop-modal" v-drag draggable="false">
      <el-button>jajajajc</el-button>
      <el-button>jajajajc</el-button>
      <el-button>jajajajc</el-button>
      <el-button>jajajajc</el-button>
      <el-button>jajajajc</el-button>
      <el-button>jajajajc</el-button>
      <el-button>jajajajc</el-button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {};
  },
  //自定义指令
  directives: {
    drag: {
      // 指令的定义
      bind: function (el) {
        let oDiv = el; // 获取当前元素
        oDiv.onmousedown = (e) => {
          // 算出鼠标相对元素的位置
          let disX = e.clientX - oDiv.offsetLeft;
          let disY = e.clientY - oDiv.offsetTop;
          console.log("本身的宽高", oDiv.clientHeight);

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

            if (left <= 0) {
              left = 0;
            } else if (
              left >=
              document.documentElement.clientWidth - oDiv.clientWidth
            ) {
              //document.documentElement.clientWidth 屏幕的可视宽度
              left = document.documentElement.clientWidth - oDiv.clientWidth;
            }
            if (top <= 0) {
              top = 0;
            } else if (
              top >=
              document.documentElement.clientHeight - oDiv.clientHeight
            ) {
              // document.documentElement.clientHeight 屏幕的可视高度
              top = document.documentElement.clientHeight - oDiv.clientHeight;
            }

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

          document.onmouseup = (e) => {
            document.onmousemove = null;
            document.onmouseup = null;
          };
        };
      },
    },
  },
};
</script>
<style lang="scss" scoped>
.crop-modal {
  position: fixed;
  left: 0;
  top: 0;
  z-index: 99;
  width: 200px;
  height: 200px;
  background-color: yellow;
  color: green;
}
</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值