html
<template>
<div>
bgygyig
<div id='parent' ref="pondModel">
<div id="sonModel" ref="sonNode" @mousedown="move"></div>
</div>
</div>
</template>
<script>
export default {
data: () => ({}),
methods: {
move(e) {
let odiv = e.target
let disX = e.clientX - odiv.offsetLeft
let disY = e.clientY - odiv.offsetTop
document.onmousemove = (e) => {
// console.log(this.$refs.pondModel.offsetHeight)
//计算元素位置(需要判断临界值)
let left = e.clientX - disX;
let top = e.clientY - disY;
console.log(top, 'top')
console.log(left, 'left')
let {
offsetHeight: pondModelHeight,
offsetWidth: pondModelWidth,
} = this.$refs.pondModel;
let {
offsetHeight: sonNodeHeight,
offsetWidth: sonNodeWidth,
} = odiv;
// 左上角(left)
if (left < 0) {
left = 0;
}
if (top < 0) {
top = 0;
}
// 左下角
if (top > pondModelHeight - sonNodeHeight) {
top= pondModelHeight - sonNodeHeight
// top = pondModelHeight - sonNodeHeight - sonNodeHeight / 2;
// 正常的是 pondModelHeight - sonNodeHeight 但是我的dom 会超出半个所以我这加了半个距离 没找到原因
}
if (left > pondModelWidth - sonNodeWidth) {
left =pondModelWidth - sonNodeWidth
// left = pondModelWidth - sonNodeWidth - sonNodeWidth / 2;
// 正常的是 pondModelWidth - sonNodeWidth 但是我的dom 会超出半个所以我这加了半个距离 没找到原因
}
odiv.style.left = left + 'px'
odiv.style.top = top + 'px'
odiv.style.zIndex = 999
}
document.onmouseup = (e) => {
document.onmousemove = null
document.onmouseup = null
odiv.style.zIndex = 1
odiv = null
}
},
}
}
</script>
<style lang="scss" scoped>
#parent {
width: 500px;
height: 500px;
border: 1px solid red;
position: relative;
#sonModel {
width: 50px;
height: 50px;
background: blue;
position: absolute;
}
}
</style>
效果图: