Vue 移动端的长按与触摸事件

4,658 阅读1分钟

Vue 移动端的长按与触摸事件

博客说明

文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢!

说明

在手机端的需求难免会遇到与手势相关的,比如div的长按和单击事件,长按可能是分享或者删除等操作,一般的形式是通过弹窗来展现。

实现

其实主要是利用dom的触摸事件,touchstart,touchmove,touchend

代码

<template>
  <div>
    <div class="btn-long" @touchstart="handlerTouchstart" @touchmove="handlerTouchmove" @touchend="handlerTouchend">长按我</div>
    <div v-if="clickShow">单击</div>
    <div v-if="longClickShow">双击</div>
  </div>
</template><script>export default {
  name: 'LongTouch',
  data () {
    return {
      // 定时器
      loop: 0,
      clickShow: false,
      longClickShow: false
    }
  },
  methods: {
    handlerTouchstart () {
      this.loop = setTimeout(() => {
        this.loop = 0
        // 执行长按要执行的内容
        this.clickShow = false
        this.longClickShow = true
      }, 500) // 定时的时间
      return false
    },
    handlerTouchmove () {
      // 清除定时器
      clearTimeout(this.loop)
      this.loop = 0
    },
    handlerTouchend () {
      // 清除定时器
      clearTimeout(this.loop)
      if (this.loop !== 0) {
        // 单击操作
        this.clickShow = true
        this.longClickShow = false
      }
    }
  }
}
</script><style scoped>.btn-long {
  width: 200px;
  height: 30px;
  background-color: red;
}
</style>

演示

image-20210811175110960

发现在长按时,会出现选中文字的效果,这比较影响体验。

优化体验

在css中加入样式,这样就不会出现选中的效果了。

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

感谢

万能的网络

以及勤劳的自己,个人博客GitHub测试GitHub

公众号-归子莫,小程序-小归博客