效果演示:
前置知识理解图示:
代码1:
<template>
<div class='container'>
<div id="box1"></div>
</div>
</template>
<script>
export default {
data () {
return {
}
},
mounted () {
this.moveEle()
},
methods: {
moveEle () {
const box1 = document.getElementById('box1')
box1.onmousedown = (e) => {
// 计算鼠标到元素X,Y距离
const X = e.clientX - box1.offsetLeft
const Y = e.clientY - box1.offsetTop
const maxWidth = document.body.clientWidth - box1.offsetWidth
const maxHeight = document.documentElement.clientHeight - box1.offsetHeight
document.onmousemove = (event) => {
event = event || window.event
// 设置偏移量
let left = event.clientX - X
let top = event.clientY - Y
if (left < 0) {
left = 0
} else if (left > maxWidth) {
left = maxWidth
}
if (top < 0) {
top = 0
} else if (top > maxHeight) {
top = maxHeight
}
// 修改box1的位置
box1.style.left = left + 'px'
box1.style.top = top + 'px'
}
document.onmouseup = () => {
// 取消document的onmousemove和onmouseup事件 !!!
document.onmousemove = null
document.onmouseup = null
}
}
}
}
}
</script>
<style scoped lang='scss'>
#box1{
width: 100px;
height: 100px;
left:10px;
top:10px;
background-color: red;
position: absolute;
}
</style>
代码2:
<template>
<div class='container'>
<div id="box1" @mousedown="moveEle"></div>
</div>
</template>
<script>
export default {
data () {
return {
}
},
methods: {
moveEle (e) {
const box1 = document.getElementById('box1')
// 计算鼠标到元素X,Y距离
const X = e.clientX - box1.offsetLeft
const Y = e.clientY - box1.offsetTop
const maxWidth = document.body.clientWidth - box1.offsetWidth
const maxHeight = document.documentElement.clientHeight - box1.offsetHeight
document.onmousemove = (event) => {
event = event || window.event
// 设置偏移量
let left = event.clientX - X
let top = event.clientY - Y
// 控制在视图之内
if (left < 0) {
left = 0
} else if (left > maxWidth) {
left = maxWidth
}
if (top < 0) {
top = 0
} else if (top > maxHeight) {
top = maxHeight
}
// 修改box1的位置
box1.style.left = left + 'px'
box1.style.top = top + 'px'
}
document.onmouseup = () => {
// 取消document的onmousemove和onmouseup事件 !!!
document.onmousemove = null
document.onmouseup = null
}
}
}
}
</script>
<style scoped lang='scss'>
#box1{
width: 100px;
height: 100px;
left:10px;
top:10px;
background-color: red;
position: absolute;
}
</style>