![](/img/trans.png)
[英]How to find out the actual event.target of touchmove javascript event?
[英]Javascript touchmove event not working after event.target moved in DOM in touchstart
我在svg
元素中有幾個svg use
元素, 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
事件不會觸發,直到我第二次觸摸屏幕,大概是因為touchstart
處理程序中的appendChild()
調用此時沒有改變任何東西?
我要使事件無效嗎? 我應該如何處理這種情況?
編輯:
JSFiddle 示例。 // 將 append_child 設置為 true/false 以查看行為
我用@JanStránský 建議的修改形式規避了這個問題。 我放置了一個覆蓋整個拖動區域的透明 svg 矩形作為拖動表面,並將其列在 svg 元素列表的末尾。
然后在處理touchstart
時,我使用鼠標 position 來確定用戶選擇了這個清晰的 svg 矩形下方的哪個 svg 元素。 然后我調用parentSVG.insertBefore(selected, clear_rect)
以便該元素被繪制在所有其他元素之上但在此拖動表面之下(因此后續拖動將起作用)。
可拖動元素全部布置在(並對齊)網格中,因此鼠標 position -> 選定元素很容易確定。 否則,您可能需要按照建議為每個可拖動元素使用一個清晰的矩形。
這個解決方案似乎阻止我使用 CSS 功能cursor: grab;
當在元素上方時,因為大的阻力表面擋住了路。 也許我會手動實現它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.