vue页面采用原生方式拖动

原创
09/30 14:24
阅读数 19

主要的难点是怎么获取要拖动的元素,e.target是获取的目标元素,可以采用while循环

      var el = e.target
      while(el && el.classList && !el.classList.contains("drag")){
        el = el.parentNode
      }
      console.log(el)

完整代码

<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>
  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
      }
    })
  },
    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)
            }
          }
        }
    }, 

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部