移動端事件物件touches的誤區

2021-09-22 11:07:58 字數 2799 閱讀 1601

不想長篇大論,也是自己遺留下的乙個錯誤的理解

在移動端觸屏事件有四個

//

手勢事件

touchstart //當手指接觸螢幕時觸發

touchmove //

當已經接觸螢幕的手指開始移動後觸發

touchend //

當手指離開螢幕時觸發

當然還有個touchcancel事件,但是我測試後,並沒發現有什麼卵用

每個觸控事件物件中都包括了touches這個屬性,用於描述前位於螢幕上的所有手指的乙個列表

那麼獲取當前事件物件我們習慣性的使用  event = event.touches[0] ,我記得在很多年前事件物件必須在touches中獲取才可以

在單指操作中,event.touches[0] 是沒問題的,貌似正確的這個寫法就一直遺留下來了

直到遇到了這樣乙個效果:模擬支付寶快捷支付的鍵盤~

移動端因為偽類:active失效的問題,我才用了js動態處理active的效果

問題就出現了:多個手指同時操作,active亂套了

簡單描述下問題:

1-9數字鍵盤

單指通過按下數字1,按住不鬆手,再單指按住數字2,按下並鬆手,此時觸發了數字1

同時按下2個數字鍵,鬆手後2個touchend都丟失,不響應了

測試的結果:測試手機 iphone 6 plus 、 安卓酷派

先看單指操作,touchstart 與touchend 的處理,按下數字1後鬆手

[log] : start的手指數量: 1[log] : start touches物件的textcontent值 :1[log] : 當前start手指對應的textcontent值: 1[log] : 

[log] : end的手指數量: 0[log] : 當前end手指對應的textcontent值: 1

觀察:

touchstart :

e.touches.length 的長度是1

touches列表中只有乙個 事件物件,並且對應的值是1

直接通過e.traget.textcontent 獲取的值也是1

touchend :

e.touches.length 的長度是0

touches列表因為沒有長度,因為沒有值

直接通過e.traget.textcontent 獲取的值也是1

三根手指操作:touchstart 與touchend 的處理

按下的順序: 數字鍵 1,2,3

鬆手的順序: 數字鍵 3,2,1,

touchstart  數字鍵 1,2,3

[log] : start的手指數量: 1[log] : start touches物件的textcontent值 :1[log] : 當前start手指對應的textcontent值: 1[log] : 

[log] : start的手指數量: 2[log] : start touches物件的textcontent值 :1[log] : start touches物件的textcontent值 :2[log] : 當前start手指對應的textcontent值: 2[log] :

[log] : start的手指數量: 3[log] : start touches物件的textcontent值 :1[log] : start touches物件的textcontent值 :2[log] : start touches物件的textcontent值 :3[log] : 當前start手指對應的textcontent值: 3

e.touches.length 的長度是隨著手指的觸點增加而遞增

e.touches列表中保留了所有觸發手勢的事件物件的總數

直接通過e.traget.textcontent 獲取的是當前的元素物件的值

touchend 數字鍵 3,2,1,

[log] : end的手指數量: 2[log] : end touches物件的textcontent值 :1[log] : end touches物件的textcontent值 :2[log] : 當前end手指對應的textcontent值: 3[log] : 

[log] : end的手指數量: 1[log] : end touches物件的textcontent值 :1[log] : 當前end手指對應的textcontent值: 2[log] :

[log] : end的手指數量: 0[log] : 當前end手指對應的textcontent值: 1

e.touches.length 的長度是隨著手指的觸發減少

touches列表中保留了所有觸發手勢的事件物件的總數

直接通過e.traget.textcontent 獲取的是當前的元素物件的值

總結:

e.touches確實能保留所有觸發點的事件物件

touchend 事件中得到的是乙個touches的最終值,也就是delete後的列表,所以獲取到的touches.length已經減少了,相當於--touches的處理後結果

touches[0] 並不能獲取到當前的指向的手勢,因為是乙個列表,不能確定是哪個乙個引用

最終還是通過e.traget取值就可以了。。。。。

移動端事件物件touches的誤區

不想長篇大論,也是自己遺留下的乙個錯誤的理解 在移動端觸屏事件有四個 手勢事件 touchstart 當手指接觸螢幕時觸發 touchmove 當已經接觸螢幕的手指開始移動後觸發 touchend 當手指離開螢幕時觸發 當然還有個touchcancel事件,但是我測試後,並沒發現有什麼卵用 每個觸控...

移動端事件(一) 移動端事件和物件

在我們開始用原聲js寫移動端輪播前,我們先了解一些移動端的基礎。touch事件 touchevents物件 滑屏的思想與實現 移動端touch事件 let box document.queryselector box touchstart mousedown 手指觸碰元素 touchmove mou...

移動端事件

移動端事件 onclick 移動端也可以使用onclick事件,但是查閱資料上說會有300ms的延遲,究竟是不是有待考究。ontouchstart 相當於pc端的onmousedown,詳細可參照先前寫的文件 事件 下同 ontouchend 相當於pc端的onmouseup.ontouchmove...