`pointermove` event not working with touch. Why not?

前端 未结 1 1727
太阳男子
太阳男子 2020-12-29 06:03

I have this pen:

https://codepen.io/anon/pen/eyKeqK

If you try it on a touch-screen device (f.e. visit the pen on your phone) you\'ll notice that when you dr

相关标签:
1条回答
  • 2020-12-29 07:00

    On the MDN documentation page about pointermove, there's this line:

    The pointermove event is fired when a pointer changes coordinates, and the pointer has not been canceled by a browser touch-action.

    source, emphasis mine

    After a short period of time, the (mobile) browser will claim the pointermove event for "native" behavior like panning the page.

    The designed, simple solution is to use the css property touch-action and set it to none on the container that has the event handler.

    Here's the css property added to your codepen: https://codepen.io/anon/pen/XVBMvL

    Or in a simplified example:

    • Set your browser to emulate touch (in Chrome, dev. tools > Sensors > Touch)
    • Start an interaction in the left part, and the dot will follow your finger
    • Start an interaction in the right part, and you'll notice it will quickly fail like in the provided example

    var dot = document.querySelector(".dot")
    document.body.addEventListener("pointermove", function(ev) {
      dot.style.transform = `translate3d(${ev.clientX}px, ${ev.clientY}px, 0)`;
    
    }, false);
    * { margin: 0; padding: 0 }
    
    .wrapper { 
      display: flex; 
      height: 100vh;
    }
    
    .hasTouchAction, 
    .noTouchAction {
      flex-grow: 1;
      text-align: center;
      background: #efefef;
    }
    
    .hasTouchAction {
      touch-action: none;
    }
    
    .noTouchAction {
      background: #ccc;
    }
    
    .dot {
      width: 16px;
      height: 16px;
      border-radius: 50%;
      background: red;
      position: absolute;
      top: -8px;
      left: -8px;
    }
    <div class="wrapper">
      <div class="hasTouchAction">
        With <code>touch-action: none</code>
      </div>
    
      <div class="noTouchAction">
        Without <code>touch-action</code>
      </div>
    </div>
    
    <div class="dot"></div>

    Make sure you don't break important things and hurt accessibility. Also spend some time to investigate browser support. This worked for me with touch emulated events in Chrome, but might not work in every browser...

    0 讨论(0)
提交回复
热议问题