【问题标题】:Moving an image when the user moves the finger over document当用户在文档上移动手指时移动图像
【发布时间】:2018-07-26 13:03:35
【问题描述】:

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

 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);
}

但图像仅在用户单击然后停止时移动一次。我怎样才能通过触摸继续移动图像。

【问题讨论】:

  • 我觉得你只需要绑定到touchmove,试试去掉start和end的监听器

标签: javascript android css touch-event


【解决方案1】:

一般来说,我会建议使用 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    相关资源
    最近更新 更多