我想在触摸式移动设备上移动图像,例如当用户在页面上移动手指时,图像保持移动并始终停留在用户手指位置,就像Web光标一样,我正在使用以下代码:>
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);
}
,但是当用户单击然后停止时,图像仅移动一次。如何保持触摸移动图像。
答案 0 :(得分: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
});
可拖动位置是您要移动的对象的类名。另外,我想指出的是,在您的代码中,您将事件监听器像这样document.addEventListener('touchmove', this.onMouseMove);
附加到了文档中,这会将事件监听器添加到了文档中,而不是添加任何特定的对象,因此它并不能真正帮助您移动个人元素。如果要将事件附加到特定元素,则需要像这样引用该元素:
let el = document.getElementById('my-el');
el.addEventListener('touchmove', onMouseMove);