html部分
<template>
<div ref="content">
<div class="signImg" @mousedown="moveDown"></div>
</div>
</template>
css部分
<style lang="scss" scoped>
body,html{
height: 100%;
}
.content{
position: relative;
top: 0;
left: 0;
width:700px;
height: 1000px;
border:1px solid black;
}
.signImg{
position: absolute;
bottom: 120px;
right: 120px;
background-color: red;
width: 100px;
height:100px;
}
</style>
js部分
data () {
return {
bottom: 120, // 拖拽元素的初始位置
right: 120
}
},
methods: {
moveDown (e) {
e.preventDefault()
const ele = e.target
const _this = this
// 向左移动的最大距离
const maxY = _this.$refs.content.offsetHeight - ele.offsetHeight - 20
// 向上移动的最大距离
const maxX = _this.$refs.content.offsetWidth - ele.offsetWidth - 20
// 鼠标位于电脑屏幕的初始位置
const initX = document.documentElement.clientWidth - e.clientX
const initY = document.documentElement.clientHeight - e.clientY
// 鼠标开始移动
document.onmousemove = function (even) {
// 当前的鼠标鼠标位于电脑屏幕的位置
const curX = document.documentElement.clientWidth - even.clientX
const curY = document.documentElement.clientHeight - even.clientY
// 当前鼠标移动的距离
const left = curX - initX
const height = curY - initY
if (_this.right + left > maxX) {
// 左边界限制
ele.style.right = maxX + 'px'
} else if (_this.right + left < 10) {
// 右边界限制
ele.style.right = 10 + 'px'
} else {
ele.style.right = _this.right + left + 'px'
}
if (_this.bottom + height > maxY) {
// 上边界限制
ele.style.bottom = maxY + 'px'
} else if (_this.bottom + height < 10) {
// 下边界限制
ele.style.bottom = 10 + 'px'
} else {
ele.style.bottom = _this.bottom + height + 'px'
}
}
document.onmouseup = function (even) {
// 获取鼠标抬起时拖拽元素的位置
if (ele.style.right) {
_this.right = Number.parseInt(ele.style.right)
}
if (ele.style.bottom) {
_this.bottom = Number.parseInt(ele.style.bottom)
}
// 关闭事件
document.onmousemove = null
document.onmouseup = null
}
},
}