Vue-drag

九宫格拖拽

by bb7bb

HTML

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.5.2/animate.min.css">
<div id="app">
  <div class="container">
    <transition>
      <div class="block animated" :style="{top:this.positionY,left:this.positionX,gridArea:'main2'}" @mousedown="move" ref="block">
        {{positionX}}
        {{positionY}}
      </div>
    </transition>
  </div>
</div>

CSS

.container {
  position: relative;
  display: grid;
  width: 300px;
  height: 300px;
  grid-template-columns: 100px 100px 100px;
  grid-template-rows: 100px 100px 100px;
  grid-template-areas: "head1 head2 head3" "main1 main2 main3" "footer1 footer2 footer3";
  /*grid-template-areas: none;*/
  border: 1px solid #000;
  margin: 50px auto;
}

.block {
  position: absolute;
  width: 100px;
  height: 100px;
  display: flex;
  justify-content: center;
  justify-items: center;
  align-items: center;
  align-content: center;
  user-select: none;
  background: olivedrab;
  border: 1px solid #000
}

Vue

new Vue({
  el: "#app",
  data: {
    positionX:0,
    positionY:0,
  },
  methods: {
  	move(e){
      let oDiv = e.target;      //获取点击的目标元素
      let gDiv = e.path[1];     //获取点击元素的父级元素
      let disX = e.clientX - 0;
      let disY = e.clientY - 0;
      document.onmousemove = (e)=>{
        let left = e.clientX - disX;
        let top = e.clientY - disY;
        switch (oDiv.style.gridArea){
          case "head1 / head1 / head1 / head1":this.rangeOfHead1(left,top,oDiv);break;
          case "head2 / head2 / head2 / head2":this.rangeOfHead2(left,top,oDiv);break;
          case "head3 / head3 / head3 / head3":this.rangeOfHead3(left,top,oDiv);break;
          case "main1 / main1 / main1 / main1":this.rangeOfMain1(left,top,oDiv);break;
          case "main2 / main2 / main2 / main2":this.rangeOfMain2(left,top,oDiv);break;
          case "main3 / main3 / main3 / main3":this.rangeOfMain3(left,top,oDiv);break;
          case "footer1 / footer1 / footer1 / footer1":this.rangeOfFooter1(left,top,oDiv);break;
          case "footer2 / footer2 / footer2 / footer2":this.rangeOfFooter2(left,top,oDiv);break;
          case "footer3 / footer3 / footer3 / footer3":this.rangeOfFooter3(left,top,oDiv);break;
        }
      };
      document.onmouseup = (e)=>{
        if(e.clientY-gDiv.offsetTop<100&&e.clientX-gDiv.offsetLeft<100){
          this.changeBlock("head1",oDiv);
        }else if(e.clientY-gDiv.offsetTop>100&&e.clientX-gDiv.offsetLeft<100&&e.clientY-gDiv.offsetTop<200){
          this.changeBlock("main1",oDiv);
        }else if(e.clientY-gDiv.offsetTop>200&&e.clientX-gDiv.offsetLeft<100){
          this.changeBlock("footer1",oDiv);
        }else if(e.clientY-gDiv.offsetTop<100&&e.clientX-gDiv.offsetLeft>100&&e.clientX-gDiv.offsetLeft<200){
          this.changeBlock("head2",oDiv);
        }else if(e.clientY-gDiv.offsetTop<100&&e.clientX-gDiv.offsetLeft>200){
          this.changeBlock("head3",oDiv);
        }else...