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



我想在移动设备中触摸移动图像,就像当任何用户将手指移动到页面上时,图像保持移动并始终停留在用户手指的位置,就像网络光标一样,我使用的代码是:

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

最新更新