此文為本人原創,如若雷同,純屬巧合!歡迎轉載,轉載請注明出處,謝謝!
在項目過程中,封裝touch事件時,發現了touch事件與mouse等事件的一些區別,且touch事件在某情況下不會觸發touchend,上測試代碼:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>demo</title> <style> #div{ width: 400px; height: 400px; background-color: red; } #divchild{ width: 200px; height: 200px; background-color: blue; } </style></head><body onselectstart ="return false;" onmousedown="return false;" oncontextmenu= "return false;"> <div id='div'><div id='divchild'></div></div> <script> window.onload = function(){ var div = document.getElementById('div'); var child = document.getElementById('divchild'); div.addEventListener('touchstart',function(e){ setTimeout(function(){ child.remove(); },1000); console.log('觸發了touchstart'); console.log(e.target); }); div.addEventListener('touchend',function(e){ console.log('觸發了touchend'); console.log(e.target); }); } </script></body></html>測試瀏覽器:Chrome56;
1.測試方式:首先點擊藍色區域并保持長按,待藍色區域消失時停止長按,會發現touchend事件并沒有觸發;
2.刷新,按照步驟1的方式點擊紅色區域,觸發touchend事件;
3.將Demo中touchestart touchend分別替換為mousedown及mouseup,再進行步驟1 2,在移動端模式和非移動端模式(不知道該不該這樣稱呼,見諒)mouse事件有著不一樣的結果,非手機模式下兩個事件都正常觸發,但移動端模式下,mouseup事件長按始終不會觸發(短按會觸發,未使用安卓系統測試),此行為讓我感覺很怪異,個人判斷可能與移動端click事件300ms延遲有關系; touch測試結果 touch測試結果 mouse測試結果 mouse測試結果
從測試可以看出,在demo中,若touchend觸發前將e.target元素刪除,將終止touch后續事件(touchmove touchend)的觸發(原因應該是target被刪除無法捕獲或冒泡到監聽元素),可得出touchstart touchmove touchend三個事件為聯動事件(自己起的名字),這三個事件(或許還有一個touchcancel)共用一個target,即在事件觸發前并不會重新獲取target,沿用上一個事件的target;而在非移動端的mousedown及mouseup事件為獨立事件(自己起得名字)–應該會在觸發前重新獲取target,而在移動端測試下行為個人認為頗為怪異,想不明白,只是認為可能和click的300ms延遲有關系。
由于本人才疏學淺,若存在錯誤歡迎批評指正,在此不勝感激!新聞熱點
疑難解答