特定的区域内移动 div
<template>
<div>
<div id="moveDiv" ref="moveDiv">
<span
v-for="(item, index) in 2"
:key="index"
@mousedown="move"
:class="'div' + index"
:style="movePosition[index]"
></span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
movePosition: [
{
className: "div0",
left: "78px",
top: "25px",
},
{
className: "div1",
left: "80px",
top: "100px",
},
],
newPostion: [],
};
},
methods: {
move(e) {
let odiv = e.target;
let disX = e.clientX - odiv.offsetLeft;
let disY = e.clientY - odiv.offsetTop;
document.onmousemove = (e) => {
let left = e.clientX - disX;
let top = e.clientY - disY;
let { offsetHeight: pondModelHeight, offsetWidth: pondModelWidth } =
this.$refs.moveDiv;
let { offsetHeight: sonNodeHeight, offsetWidth: sonNodeWidth } = odiv;
// 左上角(left)
if (left < 0) {
left = 0;
}
if (top < 0) {
top = 0;
}
// 左下角
if (top > pondModelHeight - sonNodeHeight) {
top = pondModelHeight - sonNodeHeight;
}
if (left > pondModelWidth - sonNodeWidth) {
left = pondModelWidth - sonNodeWidth;
}
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;
console.log(odiv.style.left);
console.log(odiv.className);
this.newPostion.push({
className: odiv.className,
left: odiv.style.left,
top: odiv.style.top,
});
odiv = null;
};
},
},
};
</script>
<style lang="scss" scoped>
#moveDiv {
width: 500px;
height: 500px;
position: relative;
border: 1px solid #000;
}
#moveDiv span {
width: 50px;
height: 50px;
background: red;
position: absolute;
cursor: move;
}
</style>
加班万岁!