移動端事件對象touches的誤區


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

在移動端觸屏事件有四個

// 手勢事件
touchstart  //當手指接觸屏幕時觸發
touchmove   //當已經接觸屏幕的手指開始移動后觸發
touchend    //當手指離開屏幕時觸發

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

每個觸摸事件對象中都包括了touches這個屬性,用於描述前位於屏幕上的所有手指的一個列表

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

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

 

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

image

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

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

簡單描述下問題:

1-9數字鍵盤

  1. 單指通過按下數字1,按住不松手,再單指按住數字2,按下並松手,此時觸發了數字1
  2. 同時按下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取值就可以了。。。。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM