通过 touchstart & click 模拟长按事件

2023-06-08  本文已影响0人  DeadMoon

正常模拟一个长按事件,我们是通过 toushstart & touchend 触发时间差来实现, 今天在开发组件库时看到字节的组件库模拟长按事件的实现, 记录一下

<body>
  <button>长按</button>
  <script>
    let timer
    document.querySelector('button').addEventListener('touchstart', handleTouchStart)
    document.querySelector('button').addEventListener('click', handleClick)
    function handleTouchStart() {
      timer = setTimeout(() => {
        timer = 0
        console.log('longpress')
      }, 1000)
    }

    function handleClick() {
      if (timer !== 0) {
        clearTimeout(timer)
      }
    }
  </script>
</body>
上一篇下一篇

猜你喜欢

热点阅读