隨著手機與平板的普及,觸控手勢已成為前端開發不可避免的知識。本文做了一個最簡單的示例,帶你直接認識 touchmove 事件——這是手指在螢幕上滑動時觸發的事件。
手機或其他觸控裝置掃描二維碼即可體驗:

使用三根手指一起滑動的效果圖:

touches 是一份「目前螢幕上所有手指」的清單,targetTouches 則只包含落在該元素上的手指。因此用 touches.length 就能判斷是幾指操作,這正是多指手勢的判斷基礎。event.preventDefault(),或改用 CSS 的 touch-action 屬性來關閉預設行為,後者效能更好。touches[0].clientX 減去 touchstart 時記下的起始 X 座標。本示例彈出的 Touch 事件說明請參考:https://hovertree.com/jsdoc/touch.htm
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>js 觸屏 touchmove 手勢事件</title>
<meta charset="utf-8">
<style>
#hovertreechuping {
min-width: 300px;
min-height: 300px;
background-color: darkgreen;
color: white;
text-align: center;
line-height: 50px;
}
.hovertreeinfo { text-align: center; }
.hovertreeinfo a { color: blue; }
</style>
</head>
<body>
<div id="hovertreechuping">
提示:請在本區域內觸摸滑動手指。請使用手機等觸屏設備。
可以使用一根手指滑動,也可以使用多根手指滑動。
</div>
<div class="hovertreeinfo">
<a href="https://hovertree.com/">何問起</a>
<a href="https://hovertree.com/menu/texiao/">網頁特效</a>
<a href="https://hovertree.com/h/bjaf/0k3j0n95.htm">代碼說明</a>
</div>
<script type="text/javascript">
function hovertreeMove(event) {
alert("在元素區內觸發了滑動事件。目前螢幕上共有 "
+ event.touches.length + " 根手指。");
}
document.getElementById("hovertreechuping")
.addEventListener("touchmove", hovertreeMove);
</script>
</body>
</html>
參考資料:
提醒一下,示例中直接用 alert 是為了最直觀地觀察觸發時機與手指數量,實際專案中請改用 DOM 更新畫面,因為 alert 會中斷所有後續事件處理,滑動體驗會完全卡住。