移动端如何实现onTap和onLongTap的事件触发

1. 背景

最近项目上有需要在移动端监听onTaponLongTap的需求,然后自己摸索了一下,实现了一个自定义事件监听,源码如下

2. 源码

;(function() {
  // 默认长按多久之后触发 onTap 和 onLongTap
  let DURATION = 300
  /**
   * 初始化事件监听
   * @example
   * initEvent({ duration: 300 })
   */
  function initEvent(options) {
    if (!isNaN(options.duration) && options.duration > 0) {
      DURATION = options.duration
    }
    for (let node of document.body.childNodes)  {
      if (node.nodeType === 1) bindTapEvent(node)
    }
  }

  /**
   * 绑定 onTap 和 onLongTap 事件,默认 300ms 之前是点击;之后是长按
   * @param {HTMLElement} node
   */
  function bindTapEvent(node) {
    const ON_TAP_NAME = 'tap'
    const ON_LONG_TAP_NAME = 'longtap'
    // 找到 onTap
    const onTap = node.getAttribute(`on${ON_TAP_NAME}`)
    // 找到 onLongTap
    const onLongTap = node.getAttribute(`on${ON_LONG_TAP_NAME}`)
    // 创建 touchstart 和 touchend 监听
    node.addEventListener(
      'touchstart',
      e => {
        this.startTouchTime = Date.now()
      },
      false
    )

    node.addEventListener(
      'touchend',
      e => {
        this.endTouchTime = Date.now()
        const diff = this.endTouchTime - this.startTouchTime
        if (diff <= DURATION) {
          createCustomEventAndEmit(ON_TAP_NAME, node)
          if (onTap) eval(onTap)
        } else {
          createCustomEventAndEmit(ON_LONG_TAP_NAME, node)
          if (onLongTap) eval(onLongTap)
        }
      },
      false
    )
  }

  /**
   * 创建自定义事件,并触发该事件
   * @param {String} eventName - 自定义事件名称
   * @param {HTMLDivElement} element - 元素节点
   * @returns {void}
   */
  function createCustomEventAndEmit(eventName, element) {
    const event = document.createEvent('Event')
    event.initEvent(eventName, false, false)
    element.dispatchEvent(event)
  }

  window.initEvent = initEvent

  return { initEvent }
})()

3. 使用方法


<button id='btn'>点我试试</button>

<script>
// 1. 引入上面的源码,可以放到一个单独的js中

// 2. 执行事件初始化
initEvent({ duration: 300 })

// 3.1 给要实现的元素添加 tap 的事件监听
document.getElementById('tap', e => {
  console.log('监听到 tap 事件', e)
}, false)

// 3.2 也可以给元素添加 `ontap='alert(123213)'`
</script>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

潇洒哥GG

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

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

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

打赏作者

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

抵扣说明:

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

余额充值