隨著智慧手機普及,有越來越多的手機網頁和網頁版遊戲,手機觸控、移動、旋轉等等,多種操作。一般電腦的人機互動靠的是滑鼠,而手機用的就是觸控。區別有:
- 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