Indeed, according to the docs,
If the target element is removed from the document, events will still
be targeted at it, and hence won't necessarily bubble up to the window
or document anymore. If there is any risk of an element being removed
while it is being touched, the best practice is to attach the touch
listeners directly to the target.
It turns out that the solution is to attach touchmove
and touchend
listeners to the event.target
itself, for example:
element.addEventListener("touchstart", (event) => {
const onTouchMove = () => {
// handle touchmove here
}
const onTouchEnd = () => {
event.target.removeEventListener("touchmove", onTouchMove);
event.target.removeEventListener("touchend", onTouchEnd);
// handle touchend here
}
event.target.addEventListener("touchmove", onTouchMove);
event.target.addEventListener("touchend", onTouchEnd);
// handle touchstart here
});
Even if the event.target
element is removed from the DOM, events will continue to fire normally and give correct coordinates.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…