<template>
    <img class="code" src="../../assets/img/cosc.png" @mousedown.prevent="move" :style="{'width':(width+'px'),'height':(width+'px')}">
</template>

<script>
import draggable from 'vuedraggable'
export default {
  name: "codeMove",
  components:{draggable},
  props:{
    width:Number
  },
  data(){
    return {
      currentX:0,
      currentY:0,
      desX:0,
      desY:0,
      timer:null,
      positionX:0,
      positionY:0
    }
  },
  methods:{
    move(e){
      let op = e.target;    //获取目标元素

      //算出鼠标相对元素的位置
      let disX = e.clientX - op.offsetLeft;
      let disY = e.clientY - op.offsetTop;
      document.onmousemove = (e)=>{    //鼠标按下并移动的事件
        //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
        let left = e.clientX - disX;
        let top = e.clientY - disY;
        if(left<0){
          left = 0;
        }
        if(left+this.width > 300){
          left = 300-this.width;
        }
        if(top<0){
          top = 0;
        }

        //绑定元素位置到positionX和positionY上面
        this.positionX = left;
        this.positionY = top;

        //移动当前元素
        op.style.left = left + 'px';
        op.style.top = top + 'px';
      };
      document.onmouseup = (e) => {
        document.onmousemove = null;
        document.onmouseup = null;
      };
    }
  }
}
</script>

<style scoped lang="less">
  .code{
    position: absolute;
    width: 100px;
    height: 100px;
  }
</style>
