【问题标题】:Stop TOUCHMOVE event when finger is not on the element anymore (but still pressed)当手指不再在元素上时停止 TOUCHMOVE 事件(但仍被按下)
【发布时间】:2020-05-08 08:11:39
【问题描述】:

我有一个 div(#parent),里面有 4 个子元素。 这个想法是,当我触摸 元素之一并移动手​​指时,我触发事件 (touchmove),当我将手指移到当前 之外(仍然按下时),事件应该停止。

我试图通过检查我是否触摸 或其他元素来完成这项工作,但没有运气。一旦按下并移动,我就无法在松开手指之前停止事件。

document.querySelector("#parent").addEventListener('touchmove', (e) => {
    console.log(`pressed ${e.target.getAttribute('data-dir')}`)
});

<div id="parent">
   <span data-dir="3">&uarr;</span>
   <span data-dir="0">&rarr;</span>
   <span data-dir="1">&darr;</span>
   <span data-dir="2">&larr;</span>
</div>

【问题讨论】:

    标签: javascript events controls touch-event touchmove


    【解决方案1】:
    1. 首先,您可以使用document.elementFromPoint() API 来判断您的手指是在&lt;span&gt; 的内部还是外部。
    2. 然后,您可以通过removeEventListener 停止该事件。在移动过程中,如果手指在&lt;span&gt; 之外,只需移除监听器即可。

    像这样:

    const $el = document.querySelector("#parent")
    $el.addEventListener('touchstart', function startHandler(e) {
      $el.addEventListener('touchmove', function moveHandler(e) {
          if (document.elementFromPoint(e.touches[0].clientX, e.touches[0].clientY).tagName !== 'SPAN') {
            $el.removeEventListener('touchmove', moveHandler)
          }) else {
            // do your things
          }
      });
      $el.addEventListener('touchend', function endHandler(e){
        // remove the listeners to avoid mutiple listeners
        $el.removeEventListener('touchstart', startHandler)
        $el.removeEventListener('touchmove', moveHandler)
        $el.removeEventListener('touchend', endHandler)
      })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多