拖拽前
拖拽,数字21+104为当前正在拖拽元素的left和top
上代码,注意布局要为定位,父级relative,要拖拽的元素为absolute
<template>
<div class="box">
<li @mousedown="move" v-for="(item,index) in list" :key="index" :style="{left:item.positionX+'px',top:item.positionY+'px'}">
</li>
{{positionX}}+{{positionY}}
</div>
</template>
<script>
export default {
data() {
return {
positionX:0,
positionY:0,
list:[
{id:0,positionX:0,positionY:100},
{id:1,positionX:230,positionY:100},
{id:2,positionX:460,positionY:100},
]
};
},
methods: {
move(e){
let odiv = e.target; //获取目标元素
console.log(odiv)
//算出鼠标相对元素的位置
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;
//绑定元素位置到positionX和positionY上面
this.positionX = top;
this.positionY = left;
//移动当前元素
odiv.style.left = left + 'px';
odiv.style.top = top + 'px';
};
document.onmouseup = (e) => {
document.onmousemove = null;
document.onmouseup = null;
};
}
}
};
</script>
<style scoped>
* {
margin: 0;
padding: 0;
list-style: none;
}
.box{
width: 100%;
height: 500px;
position: relative;
}
li{
position: absolute;
top: 100px;
left: 100px;
z-index: 3000;
width: 200px;
height: 200px;
background: #666;
cursor: move;
}
</style>