美文网首页
通过 touchstart & click 模拟长按事件

通过 touchstart & click 模拟长按事件

作者: DeadMoon | 来源:发表于2023-06-08 11:33 被阅读0次

    正常模拟一个长按事件,我们是通过 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>
    

    相关文章

      网友评论

          本文标题:通过 touchstart & click 模拟长按事件

          本文链接:https://www.haomeiwen.com/subject/ssxaedtx.html