vue3实现移动div

借助vue官方组件VueUse的useElementBounding()获取元素的属性。

VueUse官方文档:VueUse中文文档 | VueUse中文文档

npm i @vueuse/core

 制造一个需要移动的div,通过绝对定位进行位置定位,通过ref获取移动对象。

<div class="box"
     style="position: absolute;top: 0;left: 0;width: 30px; height: 30px;background-color: red;cursor:move;"
     ref="box"
     @mousedown="BoxMove"/>

 script部分:

// 获取对象
const box = ref<any>()

// 窗口移动
const BoxMove = (e: any) => {

  // 元素位置
  const {left: elL, top: elT} = useElementBounding(box)

  // 鼠标位置
  let x: number = e.clientX
  let y: number = e.clientY

  // 鼠标到元素左边距离
  let moveX: number = x - elL.value
  let moveY: number = y - elT.value

  document.onmousemove = function (e: any) {
    box.value.style.left = (e.clientX - moveX) + 'px'
    box.value.style.top = (e.clientY - moveY) + 'px'
  }

  document.onmouseup = function () {
    document.onmousemove = null
    document.onmouseup = null
  }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值