vue实现按钮的长按功能

实现效果图:

实现思路:

  • 给需要操作的 dom 元素添加touchstart(点击开始)touchend(点击结束)touchmove(手指移动)事件
  • 在使用touchstart(点击开始)事件的时候设置定时器,在指定时间内如果不做其他操作就视为 长按事件,执行 长按事件 的同时需要设定当前不是 单击事件,以防止touchend(点击结束)执行的时候同时出现 长按事件 和 单击事件
  • 在 touchend(点击结束)里面清除定时器,并判断是不是 单击事件
  • 在 touchmove(手指移动)里面清除定时器,并设定当前不是 单击事件

代码

HTML

<div @touchstart="gotouchstart" @touchmove="gotouchmove" @touchend="gotouchend" class="div">按钮</div>

JS

<script>
export default {
  data() {
    return {}
  },
  methods: {
    /**
     * @Description: 长按事件
     * @Author: LiuYanQiang
     */
    gotouchstart() {
      var that = this
      window.isClick = true
      clearTimeout(that.timeOut)
      that.timeOut = setTimeout(function () {
        //that.actionSheetShow=true;//修改删除弹窗出现
        that.$toast('长按你不痛么?')
        console.log('在这里执行长按事件')
        window.isClick = false
      }, 500)
    },

    /**
     * @Description: 短按事件————手释放,如果在500毫秒内就释放,则取消长按事件,此时可以执行onclick应该执行的事件
     * @Author: LiuYanQiang
     */
    gotouchend() {
      var that = this
      clearTimeout(that.timeOut)

      if (window.isClick) {
        //that.banksClick(index, item)
        that.$toast('短按就行了!')
      }
    },
    /**
     * @Description: 如果手指有移动,则取消所有事件,此时说明用户只是要移动而不是长按
     * @Author: LiuYanQiang
     */
    gotouchmove() {
      // console.log('手指移动了')
      clearTimeout(this.timeOut)
      window.isClick = false
    }
  },
  // 项目销毁前清除定时器
  beforeDestroy() {
    clearTimeout(this.timeOut)
  }
}
</script>

style(去除长按出现的文字复制影响)

    -webkit-touch-callout:none;
    -webkit-user-select:none;
    -khtml-user-select:none;
    -moz-user-select:none;
    -ms-user-select:none;
    user-select:none;

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小刘要努力(ง •̀_•́)ง

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值