The mobile end of vue realizes the drag and drop of div

Posted by mitsubishi2002 on Fri, 03 Apr 2020 04:30:33 +0200

The mobile end of vue realizes the drag and drop of div
This article describes how to achieve a floating window similar to the iPhone on the mobile side of VUE.

Relevant knowledge points

Touch start triggered when a finger is pressed on the screen

touchmove triggered when a finger is moved on the screen

touchend triggered when a finger is raised on the screen
mousedown mousemove mouseup corresponds to events on the PC side

Touch Cancel when some higher-level events occur (such as phone access or pop-up messages), the current touch operation will be cancelled, that is, touch cancel will be triggered. Generally, the game, archive and other operations will be suspended during touchcancel.

Design sketch

Implementation steps

(1) html

<template>
    <div id="customer">
  ...
    <!-- Suspended HTML -->
    <div v-if="!isShow" class="xuanfu" id="div2"
      @mousedown="down" @touchstart="down"
      @mousemove="move" @touchmove="move"
      @mouseup="end" @touchend="end"
    >
      <div class="yuanqiu">
        {{pageInfo.totalPage}}
      </div>
    </div>
  ...
  </div>
</template>

(two) JS

<script>
data() {
  return {
    flags: false,
    position: {
      x: 0,
      y: 0
    },
    nx: '', ny: '', dx: '', dy: '', xPum: '', yPum: '',
  }
}

methods: {
  // Mobile drag
  down(){
    this.flags = true;
    var touch ;
    if(event.touches){
        touch = event.touches[0];
    }else {
        touch = event;
    }
    this.position.x = touch.clientX;
    this.position.y = touch.clientY;
    this.dx = moveDiv.offsetLeft;
    this.dy = moveDiv.offsetTop;
  },
  move(){
    if(this.flags){
      var touch ;
      if(event.touches){
          touch = event.touches[0];
      }else {
          touch = event;
      }
      this.nx = touch.clientX - this.position.x;
      this.ny = touch.clientY - this.position.y;
      this.xPum = this.dx+this.nx;
      this.yPum = this.dy+this.ny;
      moveDiv.style.left = this.xPum+"px";
      moveDiv.style.top = this.yPum +"px";
      //Prevent page from sliding default events
      document.addEventListener("touchmove",function(){
          event.preventDefault();
      },false);
    }
  },
//Function when mouse is released
  end(){
    this.flags = false;
  },
}
</script>

(three) CSS

<style>
  .xuanfu {
    height: 4.5rem;
    width: 4.5rem;
    z-index: 990;
    position: fixed;
    top: 4.2rem;
    right: 3.2rem;
    border-radius: 0.8rem;
    background-color: rgba(0, 0, 0, 0.55);
  }
  .yuanqiu {
    height: 2.7rem;
    width: 2.7rem;
    border: 0.3rem solid rgba(140, 136, 136, 0.5);
    margin: 0.65rem auto;
    color: #000000;
    font-size: 1.6rem;
    line-height: 2.7rem;
    text-align: center;
    border-radius: 100%;
    background-color: #ffffff;
  }
</style>

Basically, it's not a big problem to implement JS logic well.

Topics: Mobile Vue