vue移动端拖拽的简单方案

话不多说,同事的需求,今儿早上过来敲了一会,希望对大家有用

首先该需求比较简单,在谷歌上查了一会发现结果的方法都有些复杂,因此决定用vue自带的手指点击事件处理,菜鸟选手写的比较简单,将就将就。
首先我们要用到的事件有
在这里插入图片描述
手指点击事件:touchstart
当手指放下去时,通过获取点击点信息与元素位置信息将元素中心点移动到点击点上

手指移动事件:touchmove
同上,获得两者位置信息之后想怎么操作就怎么操作,始终让元素中心点位置等于手机点击点位置就行,重点在拖动结束时的落点

拖动结束事件:touchend
当拖动事件结束时,要让元素落点位置等于我们的目标位置,这在上面的move函数中就可以实现
,而我们要在end函数中做的就是限制元素落在可是页面外面,限定其可以移动的范围,与上面的实现方法一样,也是根据两者的信息来处理,不过在这个函数中我们要加入屏幕的判定信息,即当元素中心落点离屏幕变径小于元素半径时,要将元素重定位至离屏幕变变径为0

看代码:

template:

 <div @touchstart="down" @touchmove="move" @touchend="end" id="circlebox" class="circle">
      <div class="left-line"></div>
      <div class="right-line"></div>
    </div>
    <!-- 遮罩 -->
    <div class="mask-box" v-if="showif"></div>

data:

      showif: false,
      positionX: 0,
      positionY: 0,
      innerHeight: 0,
      innerWidth: 0,

methods:

  methods: {
    /* 阻止移动端屏幕默认滑动 */
    default (e) {
      document.body.addEventListener(
        'touchmove',
        function (e) {
          e.preventDefault()
        },
        { passive: false }
      )
    },
    getThisNode () {
      let odiv = document.getElementById('circlebox')
      odiv.style.left = `${this.positionX - 30}px`
      odiv.style.top = `${this.positionY - 30}px`
    },
    down (e) {
      this.default()
      this.showif = true
      this.innerHeight = e.view.innerHeight
      this.innerWidth = e.view.innerWidth
      console.log(this.innerHeight, this.innerWidth)
      this.positionX = e.changedTouches[0].pageX
      this.positionY = e.changedTouches[0].pageY
      this.getThisNode()
      console.log(e)
    },
    move (e) {
      this.default()
      this.positionX = e.changedTouches[0].pageX
      this.positionY = e.changedTouches[0].pageY
      this.getThisNode()
    },
    end (e) {
      this.default()
      let odiv = document.getElementById('circlebox')
      if (this.positionX <= 30) {
        this.positionX = 30
      } else if (this.positionX >= this.innerWidth - 30) {
        this.positionX = this.innerWidth - 30
      } else {
        this.positionX = this.positionX
      }
      if (this.positionY <= 30) {
        this.positionY = 30
      } else if (this.positionY >= this.innerHeight - 60) {
        this.positionY = this.innerHeight - 30
      } else {
        this.positionY = this.positionY
      }
      odiv.style.left = `${this.positionX - 30}px`
      odiv.style.top = `${this.positionY - 30}px`
      this.showif = false
    }
  }

首先touch事件会返回一个事件信息:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
上面返回的是点击点在屏幕上的信息,包括点击点到页面上,屏幕上,可视范围左两侧的距离,下面的是显示的点击的元素在屏幕上的距离,包含此元素在屏幕上距离左上两侧的距离,(注:距离判定以元素左上角为准)本次需求解决方案就是通过操作以上的信息和以下的元素信息完成:
在这里插入图片描述
我们该点击元素为一个直径60的圆形元素
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43209224/article/details/88290370
今日推荐