vue移动端长按事件触发删除按钮

利用移动端的touchstart touchend touchmove 事件结合 实现长按事件的触发

<div
  class="item"
  @touchstart="gtouchstart(item, item.id, $event)"
  @touchmove="gtouchmove($event, item, item.id)"
  @touchend="gtouchend(item, item.id)"
>
<p
  class="cancel"
  v-show="item.show == 'true' && radio == item.id"
  @click="deleteHouse(item.isDefault)"
>删除</p>
gtouchstart (item, id, e) {
  this.phone = checkDevice();
  if (this.phone == "Android") {
    // 长按3秒 开始触摸
    this.timeOutEvent = 0
    this.timeOutEvent = setTimeout(() => {
      this.radio = id
      this.$set(item, 'show', 'true')
    }, 500)
  } else {
    this.moveDistance = 0 // 阻力滑动距离归0
    this.move = 0 // 移动距离归0
    this.startX = e.targetTouches[0].clientX // x轴归0
  }
},
gtouchmove (e, item, id) {
  this.phone = checkDevice();
  if (this.phone == "Android") {
    clearTimeout(this.timeOutEvent)
    this.timeOutEvent = 0
  } else {
    // 获取左滑的距离
    this.move = this.startX - e.targetTouches[0].clientX
    console.log(this.move)
    // move大于0,说明手指移动了
    if (this.move > 0) {
      // 阻止默认事件,因为有些app会有默认事件
      e.preventDefault()
      // 增加滑动阻力,尤为重要,如果不要这一步,上下滑动就会不经意触发左右滑动事件
      this.moveDistance = Math.pow(this.move, 0.8)
      // 设置滑动的最大距离,如果阻力滑动的距离大于按钮的宽度,就赋值为按钮的宽度
      if (this.moveDistance > this.distance) {
        // 如果滑动距离大于15 出现隐藏按钮
        this.radio = id
        this.$set(item, 'show', 'true')
      } else {
        // 滑动距离并没有超过按钮的一半,给我归位
        this.radio = ''
        this.$set(item, 'show', 'false')
      }
    }
  }
},
gtouchend (item, id) {
  this.phone = checkDevice();
  if (this.phone == "Android") {
    clearTimeout(this.timeOutEvent)
    this.timeOutEvent = 0
  } else {
    if (this.move == 0 && item.show == 'true') {
      // 触发点击事件
      this.$emit('deleteHouse')
    } else if (this.move > 0 && item.show == 'false') {
      // 如果滑动结束  滑动距离大于右侧按钮的一半  则出现按钮,否则隐藏按钮
      if (this.moveDistance > this.distance / 2) {
        this.radio = id
        this.$set(item, 'show', 'true')
      } else {
        // 滑动距离并没有超过按钮的一半,给我归位
        this.radio = ''
        this.$set(item, 'show', 'false')
      }
    } else {
      this.radio = ''
      this.$set(item, 'show', 'false')
    }
  }
},

实现的效果是 长按一秒显示删除按钮
在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值