隨着智能手機普及,有越來越多的手機網頁和網頁版游戲,手機觸摸、移動、旋轉等等,多種操作。一般電腦的人機交互靠的是鼠標,而手機用的就是觸摸。區別有:
- PC 端一個電腦只能有一個鼠標,而移動端有多點觸摸。
- PC 端添加效果使用 mouseup、mousedown、mousemove,而移動端使用的 touchstart、touchmove、touchend 。
一、touch事件類型
- touchstart - 手指觸摸屏幕,在元素上按下時觸發
- touchmove - 手指移動,在元素上按下之后屏幕上任意移動
- tounchend - 手指在元素上按下之后,屏幕任意位置抬起時觸發
- touchcancel - 觸摸過程中被系統取消時觸發 (很少使用)
touch 事件與mouse事件區別:
- touchstart:手指按下,mousedown:鼠標按下。
- touchmove:手指在屏幕上移動,mousemove:鼠標在網頁上移動。
- touchend:手指抬起,mouseup:鼠標彈起。
- touch:事件只能在移動端使用,mouse :事件只能在 PC 端使用。
- touchstart: 只能在綁定元素內按下觸發,touchmove、touchend可以在屏幕的任意位置執行。而 mousedown、mousemove、mouseup 都只能在綁定元素內執行。
- touchmove、touchend 只能在 touchstart 觸發后,才能執行。但是 mousemove 只要鼠標在綁定元素上,不按下也能執行。
1.1、事件綁定
使用語法:
element.addEventListener( 'eventtype' , function(){} , useCapture )
eg:使用 touchstart 示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .box{ width:200px; height:200px; border:solid 1px red; } </style> </head> <body> <div class="box"></div> <script> window.onload = function(){ let oBox = document.getElementsByClassName('box')[0] oBox.addEventListener('touchstart',function(ev){ console.log(ev) },false) } </script> </body> </html>
每個touch事件的 event 對象,提供了手指觸摸過程中的常見屬性。打印函數返回的 event 對象,發現有很多參數,如圖:

1.2、touchEvent 對象屬性
- targetTouches - 當前元素目標上 touch 列表。
- touches - 當前屏幕上的手指觸摸 touch 列表。
- changedTouches - 觸發當前事件的觸摸 touch 列表。
獲取方法:
let oBox = document.getElementsByClassName('box')[0] oBox.addEventListener('touchstart',function(ev){ console.log(ev.touches) console.log(ev.targetTouches) console.log(ev.changedTouches) },false)
上一篇文章我們介紹過,手機如何訪問電腦上本地網頁,建議使用Browsersync,手機運行網頁,手機觸摸屏幕,在元素上觸摸等觀察上述三個屬性打印情況。
我們發現它們都是一個數組,每個元素代表一個觸摸點。每個觸摸點對應的 都有一些重要的屬性,分別為:
- clientX - 觸摸點在可視區的 x 坐標。
- clientY - 觸摸點在可視區的 y 坐標。
- pageX - 觸摸點在網頁上的 x 坐標。
- pageY - 觸摸點在網頁上的 y 坐標。
- screenX - 觸摸點在屏幕中的 x 坐標。
- screenY - 觸摸點在屏幕中的 y 坐標。
- identifier - 觸摸點的唯一標識 id。
- target - 觸摸的 DOM 節點。
二、觸摸分類
很多情況下觸摸事件會分為兩種,單點觸發和多點觸發。
單點觸發,指的一個指頭在屏幕觸摸、滑動,主要應用在下拉刷新,手機端banner滑動切換等。
注意:如果是單點觸摸,但是有多個手指同時觸發,此時需要求三個點的平均值作為觸摸點。
多點觸發:多個手指同時觸摸屏幕,進行旋轉、縮放、放大、拖拽等操作。

很多情況下,觸摸事件跟鼠標事件會同時觸發,目的是為了在pc端運行的時候,沒有觸摸設備可以使用鼠標代替。如果可以支持觸摸事件,則把鼠標事件使用event.preventDefault()阻止事件發生,此時鼠標事件將失效。如果鼠標和觸摸事件都支持時,還有添加多個觸摸事件時,具體的執行順序是怎么的?
觸摸事件跟鼠標事件的觸發先后順序:
Touchstart > toucheend > mousemove > mousedown > mouseup > click