簡體   English   中英

為什么在 DOM 更改后不觸發 touchmove 事件?

[英]Why touchmove event is not fired after DOM changes?

在將我的應用程序從鼠標移動到觸摸事件時,我注意到了一些奇怪的行為。 基本上,touchmove 在 DOM 更改后停止工作。 鼠標事件在相同的情況下工作正常。 我使用 chrome 開發人員工具和 firefox 對其進行了測試。 他們似乎對結果達成了一致。 這是一個錯誤還是我錯過了什么?

我創建了非常簡單的代碼示例來證明問題與我使用的任何框架或庫無關。 我還發現了看似相關的問題,但不幸的是沒有解決方案。

觸摸演示:

 window.addEventListener("touchmove", onTouchMove, {passive: false}) document.addEventListener('DOMContentLoaded', function(){ var elem = document.getElementById("nice"); console.log(elem) elem.addEventListener("touchstart", onTouchStart) }) function onTouchMove(event) { console.log("touch move") } function onTouchStart(event) { console.log("touch start") var elem = document.getElementById("nice") elem.remove() }
 <!DOCTYPE html> <html> <body style="width: 100%; height: 100%; background-color: yellow"> <div style="position: absolute; width: 100px; height: 100px; background-color: red; left: 100px; top: 100px" id="nice"></div> </body> </html>

鼠標演示:

 window.addEventListener("mousemove", onMouseMove, {passive: false}) document.addEventListener('DOMContentLoaded', function(){ var elem = document.getElementById("nice"); console.log(elem) elem.addEventListener("mousedown", onMouseDown) }) function onMouseMove(event) { console.log("mouse move") } function onMouseDown(event) { console.log("mouse start") var elem = document.getElementById("nice") elem.remove() }
 <!DOCTYPE html> <html> <body style="width: 100%; height: 100%; background-color: yellow"> <div style="position: absolute; width: 100px; height: 100px; background-color: red; left: 100px; top: 100px" id="nice"></div> </body> </html>

從紅色方塊開始的一個連續拖動手勢應該會導致 1) 日志中的“開始”消息,2) 該方塊消失,在這種情況下是 DOM 更改 3) 日志中的“移動”消息序列。 在鼠標演示中也是如此,但在觸摸演示中,方塊消失后沒有“移動”事件。

如果您的元素被刪除,這是一種預期行為。

根據docs ,如果您刪除一個元素,事件仍將針對它,因此不一定再冒泡到窗口或文檔中。

所以如果要刪除元素,有兩種解決方案。 您可以修改“remove”方法,使其僅在觸摸過程結束之前隱藏元素,或者您可以將事件附加到目標本身。

這是一個例子,你可以看到窗口 touchmove 事件沒有出現,而元素的 touchmove 事件即使在元素被移除后也會出現。

 window.addEventListener("touchmove", onTouchMoveWindow, {passive: false}) document.addEventListener('DOMContentLoaded', function(){ var elem = document.getElementById("nice"); console.log(elem) elem.addEventListener("touchstart", onTouchStart) elem.addEventListener("touchmove", onTouchMoveElement) }) function onTouchMoveWindow(event) { console.log("touch move window") } function onTouchMoveElement(event) { console.log("touch move element") } function onTouchStart(event) { console.log("touch start") var elem = document.getElementById("nice") elem.remove() }
 <!DOCTYPE html> <html> <body style="width: 100%; height: 100%; background-color: yellow"> <div style="position: absolute; width: 100px; height: 100px; background-color: red; left: 100px; top: 100px" id="nice"></div> </body> </html>

相關問題:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM