当用户将手指移到文档上时移动图像

Moving an image when the user moves the finger over document

我想在移动设备中通过触摸移动图像,例如每当用户将手指移到页面上时,图像会一直移动并始终停留在用户手指的位置,类似于网络光标,我正在使用此代码:

 document.addEventListener('touchmove', this.onMouseMove);
 document.addEventListener('touchStart', this.onMouseMove);
 document.addEventListener('touchEnd', this.onMouseMove);

onMouseMove = (e) => {
   const img = document.getElementById('drawing-mouse-pointer');
   img.style.left = `${e.touches[0].clientX}px`;
   img.style.top = `${e.touches[0].clientY }px`;
   console.log(e.touches[0] && e.touches[0].clientY);
}

但是图像只在用户点击时移动一次然后停止。我怎样才能一直用触摸移动图像。

一般来说,我建议为此使用一个库,例如 Interact.js,因此您可以执行以下操作,而不是您所做的:

interact('.draggable')
  .draggable({
  // enable inertial throwing
  inertia: true,
  // keep the element within the area of it's parent
  restrict: {
    restriction: "parent",
    endOnly: true,
    elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
  },
  // enable autoScroll
  autoScroll: true
});

其中 draggable 是您要移动的对象的类名。另外,我想指出,在您的代码中,您像这样将事件侦听器附加到文档 document.addEventListener('touchmove', this.onMouseMove); 这会将事件侦听器添加到文档,而不是任何特定对象,因此它不会真正帮助您移动个人元素。如果要将事件附加到特定元素,则需要像这样引用该元素:

let el = document.getElementById('my-el');
el.addEventListener('touchmove', onMouseMove);