主要的难点是怎么获取要拖动的元素,e.target是获取的目标元素,可以采用while循环
代码语言:javascript复制 var el = e.target
while(el && el.classList && !el.classList.contains("drag")){
el = el.parentNode
}
console.log(el)
完整代码
代码语言:javascript复制<div class="outBox">
<div class="boxWrap">
原生拖动
<div class="drag box box1" id="001">
<div>第一行</div>
<div>第二行</div>
</div>
<div class="drag box box2" id="002">
<div>第一行</div>
<div>第二行</div>
</div>
</div>
<div>
<el-button type="primary" @click="saveHtml">保存html</el-button>
</div>
</div>
代码语言:javascript复制 mounted(){
let elWrap = document.querySelector(".boxWrap")
console.log(elWrap)
elWrap.addEventListener("mousedown",(e)=>{
var el = e.target
while(el && el.classList && !el.classList.contains("drag")){
el = el.parentNode
}
console.log(el)
let disX = e.clientX - el.offsetLeft;
let disY = e.clientY - el.offsetTop;
console.log(el.offsetLeft)
document.onmousemove = (e)=>{
let left = e.clientX-disX
console.log(left)
let top = e.clientY-disY
el.style.left = left "px"
el.style.top = top "px"
clearTimeout(this.timer)
this.timer = setTimeout(() => {
let obj = {id:el.id,left:left,top:top}
console.log(this)
this.savePositionInfo(obj)
}, 300);
}
document.onmouseup = (e)=>{
document.onmousemove = null
document.onmouseup = null
}
})
},
代码语言:javascript复制 saveHtml(){
console.log(document.querySelector(".boxWrap").innerHTML)
},
savePositionInfo(obj){
if (this.positionInfor.length == 0) {
console.log("等于0");
this.positionInfor.push(obj);
console.log(this.positionInfor)
} else {
for (let i = 0; i < this.positionInfor.length; i ) {
if (this.positionInfor[i].id == obj.id) {
this.positionInfor.splice(i,1,obj)
console.log(this.positionInfor)
return;
}
if (i == this.positionInfor.length - 1) {
this.positionInfor.push(obj);
console.log(this.positionInfor)
}
}
}
},