DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> WEB網站前端 >> 網頁特效代碼
js 觸屏 touchmove 手勢事件實例
編輯:網頁特效代碼     

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

手機或其他觸控裝置掃描二維碼即可體驗:

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

幾個必須知道的重點

  • 觸控事件共有 touchstart、touchmove、touchend、touchcancel 四個,本示例只監聽了 touchmove。
  • 事件物件上的 touches 是一份「目前螢幕上所有手指」的清單,targetTouches 則只包含落在該元素上的手指。因此用 touches.length 就能判斷是幾指操作,這正是多指手勢的判斷基礎。
  • 在觸控裝置上滑動時,瀏覽器預設會滾動頁面。若你要自訂手勢(例如做左右滑動切換),通常在 touchmove 中呼叫 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 會中斷所有後續事件處理,滑動體驗會完全卡住。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved