• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

vue.js怎么实现移动端长按事件

vue 搞代码 4年前 (2021-12-26) 33次浏览 已收录 0个评论

vue.js实现移动端长按事件的方法:

方法一:使用@touchstart@touchend

start () {
      clearTimeout(this.loop); //再次清空定时器,防止重复注册定时器
      this.loop = setTimeout(() => {
        console.log("长按了");
      }, 1000);
    },
 end () {
      clearTimeout(this.loop); //清空定时器,防止重复注册定时器
    },

备注:使用的时候注意如果是图片,建议把图片设置为背景,直接使用图片,在长按时会触发浏览器对图片的保存、分享等。

方法二:

// 指令
export default {
  install(Vue, options = {
    time: 2000,
  }) {
    Vue.directive('longpress', {
      bind: function(el, binding, vNode) {
        if (typeof binding.value !== 'function') {
          const compName = vNode.context.name
          let warn = `[longpress:] provided expression '${binding.expression}' is not afunction, but has to be `
          if (compName) { warn += `Found in component '${compName}' ` }
          console.warn(warn)
        }
        // 定义变量
        let pressTimer = null
        // 定义函数处理程序
        // 创建计时器( 1秒后执行函数 )
        let start = (e) => {
          if (e.type === 'click' && e.button !== 0) {
            return
          }
<strong style="color:transparent">来源gaodai#ma#com搞@代~码网</strong>          if (pressTimer === null) {
            pressTimer = setTimeout(() => {
              // 执行函数
              handler()
            }, options.time)
          }
        }
        // 取消计时器
        let cancel = (e) => {
          // 检查计时器是否有值
          if (pressTimer !== null) {
            clearTimeout(pressTimer)
            pressTimer = null
          }
        }
        // 运行函数
        const handler = (e) => {
          // 执行传递给指令的方法
          binding.value(e)
        }
        // 添加事件监听器
        el.addEventListener('mousedown', start)
        el.addEventListener('touchstart', start)
        // 取消计时器
        el.addEventListener('click', cancel)
        el.addEventListener('mouseout', cancel)
        el.addEventListener('touchend', cancel)
        el.addEventListener('touchcancel', cancel)
      },
    })
  },
}

方法三:vue自定义手势

如果给父元素添加v-longTap事件,点击子元素时无法触发点击事件。

以上就是vue.js怎么实现移动端长按事件的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:vue.js怎么实现移动端长按事件
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址