如何解决event.target在touchstart中的DOM中移动后,Javascript touchmove事件不起作用
我在svg use
元素中有几个svg
元素,并将touchstart/move/end
的事件处理程序附加到svg
元素上。当用户触摸屏幕上的svg use
元素并四处移动手指时,该元素将根据需要在屏幕周围移动。
//Exact code in fiddle is different,this is example
<svg id="parent" viewBox="0 0 1000 1000">
<use href="test.svg" width="100" height="100" x="100" y="100">
<use href="test2.svg" width="100" height="100" x="100" y="100">
</svg>
//Exact code in fiddle is different,this is example
let parentSVG = document.getElementById("parent");
parentSVG.addEventListener('touchstart',Handle_DragStart); //mousedown too
parentSVG.addEventListener('touchmove',Handle_Drag); //mousemove too
parentSVG.addEventListener('touchend',Handle_DragEnd); //mouseup too
问题是我希望始终将拖动的元素绘制在其他元素的上方,并且这些元素以DOM顺序绘制(DOM中的第一个元素优先)。为了解决这个问题,在我的touchstart
事件处理程序中,我将用户触摸过的元素通过appendChild()
移动到列表的末尾:
//Exact code in fiddle is different,this is example
let mid_move = false;
function Handle_DragStart (event)
{
//Needed to ignore other touch events while dragging
if(mid_move)
return;
mid_move = true;
//The event.target is the svg use element.
//It is already attached to the parentSVG.
//This just moves it to the end of the list of children.
parentSVG.appendChild(event.target);
}
这就像mousedown
和mousemove
的超级按钮,但不是touchstart
和touchmove
的超级按钮。完成此操作后,touchmove
事件将不会触发,直到我第二次触摸屏幕为止,这大概是因为appendChild()
处理程序中的touchstart
调用当时没有任何改变吗? / p>
我使事件无效吗?我应该如何处理这种情况?
编辑:
JSFiddle example. //将append_child设置为true / false以查看行为
解决方法
我用@JanStránský建议的修改形式规避了这个问题。我放置了一个覆盖整个拖动区域的透明svg矩形作为拖动表面,并将其列在svg元素列表的末尾。
然后,在处理touchstart
时,我使用鼠标的位置来确定用户选择的这个清晰的svg矩形下面的哪个svg元素。然后,我调用了parentSVG.insertBefore(selected,clear_rect)
,以便将该元素绘制在此拖动表面之下的所有其他元素之上(以便随后的拖动起作用)。
所有可拖动元素都放置在网格中(并捕捉到网格中),因此可以轻松确定鼠标位置->选择的元素。否则,按照建议,每个可拖动元素可能需要一个透明矩形。
此解决方案似乎使我无法在元素上方使用CSS功能cursor: grab;
,因为有较大的拖动表面。也许我只是手动实现它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。