vue2 实现鼠标移动拖放

<!-- 演示demo 鼠标拖放 -->
<template>
  <div class="demo" v-drag>
    <ul>
      <li>
        可拖动
      </li>
      <li>vue</li>
      <li>vue2</li>
    </ul>
  </div>
</template>

<script>
export default {
  directives: {
    drag: function(el) {
      let dragBox = el;
      dragBox.onmousedown = (e) => {
        //算出鼠标相对元素的位置
        let disX = e.clientX - dragBox.offsetLeft;
        let disY = e.clientY - dragBox.offsetTop;
        document.onmousemove = (e) => {
          //用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
          let left = e.clientX - disX;
          let top = e.clientY - disY;
          //移动当前元素
          dragBox.style.left = left + "px";
          dragBox.style.top = top + "px";
        };
        document.onmouseup = (e) => {
          //鼠标弹起来的时候不再移动
          document.onmousemove = null;
          //预防鼠标弹起来后还会循环(即预防鼠标放上去的时候还会移动)
          document.onmouseup = null;
        };
      };
    },
  },
};
</script>

<style lang="less" scoped>
.demo {
  padding: 50px;
  width: 200px;
  position: fixed;
  z-index: 10;
  top: 50%;
  right: 50%;
  background-color: #ffffff;
  cursor: move;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值