借助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
}
}