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

久未见 提交于 2019-12-03 07:01:26

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...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!