美文网首页
vue拖拽、拖放、移动元素

vue拖拽、拖放、移动元素

作者: Gaochengxin | 来源:发表于2020-06-28 11:17 被阅读0次

    方法一:

       <div :class="mapbig? 'contright bigbox':'contright'" 
              ref="contmap" @mousedown="move($event,mapbig)">
               <div class="title">数据展示 </div><div class="item" 
         @mousedown.stop="move($event,false)">    <--子元素阻止继承父元素事件-->
      </div></div>
       move(e,s){
        if(s){   //需要拖拽的元素传true
         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;
    
        //绑定元素位置到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;
      };
      }
    },
    

    方法二:

       <div class="conts" ref="dragBox" @touchstart.stop="touchstartHandle('dragBox',$event, true)" 
        @touchmove.stop="touchmoveHandle('dragBox',$event, true)">
      </div>
     touchstartHandle(refName, e, flag) { // 传false不拖拽
      if (!flag) {
        return false;
      };
      let element = e.targetTouches[0];
      // 记录点击的坐标
      this.coordinate.client = {
        x: element.clientX,
        y: element.clientY
      };
      // 记录需要移动的元素坐标
      this.coordinate.elePosition.left = this.$refs[refName].offsetLeft;
      this.coordinate.elePosition.top = this.$refs[refName].offsetTop;
    },
    touchmoveHandle(refName, e, flag) {
      if (!flag) {
        return false;
      };
      let element = e.targetTouches[0];
      // 根据初始 client 位置计算移动距离(元素移动位置=元素初始位置+光标移动后的位置-光标点击时的初始位置)
      let x = this.coordinate.elePosition.left + (element.clientX - this.coordinate.client.x);
      let y = this.coordinate.elePosition.top + (element.clientY - this.coordinate.client.y);
      // 限制可移动距离,不超出可视区域
      x = x <= 0 ? 0 : x >= innerWidth - this.$refs[refName].offsetWidth ? innerWidth - this.$refs[refName].offsetWidth : x;
      y = y <= 45 ? 45 : y >= this.$refs[refName].offsetHeight - 50 ? this.$refs[refName].offsetHeight - 10 : y;
      // 移动当前元素
      this.$refs[refName].style.left = x + 'px';
      this.$refs[refName].style.top = y + 'px';
    },

    相关文章

      网友评论

          本文标题:vue拖拽、拖放、移动元素

          本文链接:https://www.haomeiwen.com/subject/sflgzhtx.html