行動裝置與桌機的互動方式根本不同:手機靠觸摸,桌機靠滑鼠。若同一份程式要在兩端跑,就得先判斷環境,再決定要綁 touchstart 還是 mousedown。本文整理一套可直接複用的做法,並示範如何用它實作「上下滑動翻頁」。
最直覺的方式是解析 navigator.userAgent,比對常見行動裝置的特徵字串。
function isMobile() {
var sUserAgent = navigator.userAgent.toLowerCase();
var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
var bIsMidp = sUserAgent.match(/midp/i) == "midp";
var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
var bIsAndroid = sUserAgent.match(/android/i) == "android";
var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
return (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 ||
bIsUc || bIsAndroid || bIsCE || bIsWM);
}
這個寫法涵蓋了 iOS、Android、Windows Mobile、UC 瀏覽器與 midp 裝置,是流傳很廣的經典版本。
把判斷結果收斂成三個變數,後續程式碼就能用同一組名稱,不必到處寫三元運算式:
var touchStart, touchMove, touchEnd; touchStart = isMobile() ? 'touchstart' : 'mousedown'; touchMove = isMobile() ? 'touchmove' : 'mousemove'; touchEnd = isMobile() ? 'touchend' : 'mouseup';
觸摸事件的座標藏在 e.touches[0] 裡,滑鼠事件則直接在 e.pageY 上。把這段差異隔離出來,主邏輯就能保持乾淨。
touchstart: function (e) {
var e = e || window.event;
stopDefault(e); // 阻止瀏覽器預設行為
if (isMobile()) {
var touch = e.touches[0];
this.y1 = touch.pageY; // 觸摸:從 touches 陣列取
} else {
this.y1 = e.pageY; // 滑鼠:直接取
}
this.y2 = 0;
},
touchmove: function (e) {
var e = e || window.event;
stopDefault(e);
if (isMobile()) {
this.y2 = e.touches[0].pageY;
} else {
this.y2 = e.pageY;
}
},
touchend: function (e) {
var e = e || window.event;
stopDefault(e);
if (this.y2 == 0) { return; } // 沒有移動,視為點擊
var diffY = this.y2 - this.y1;
if (diffY > 50) {
this.doNext(); // 往下滑 → 下一頁
} else if (diffY < -50) {
this.doPrev(); // 往上滑 → 上一頁
}
this.y1 = 0;
this.y2 = 0;
},
這裡的 50 是滑動距離的門檻值。設得太小會讓一般點擊被誤判為滑動,設得太大則操作起來笨重;實務上可依字型大小與頁面密度微調,50–80 像素是常見區間。
function stopDefault(e) {
var e = e || window.event;
if (e.preventDefault) {
e.preventDefault(); // DOM 標準
} else {
e.returnValue = false; // 舊版 IE
}
}
在觸摸場景中,若不阻止預設行為,瀏覽器可能同時觸發頁面捲動或橡皮筋回彈效果,導致手勢判斷與原生捲動互相打架。
User Agent 判斷是為了解決歷史問題而生的手段,缺點是清單永遠追不上新裝置,且可被任意偽造。目前更推薦的方向有兩個:一是用 window.matchMedia('(pointer: coarse)') 或 CSS media query 判斷輸入裝置類型;二是直接使用 Pointer Events(pointerdown / pointermove / pointerup),它統一了滑鼠、觸摸與觸控筆的事件模型,不必再分環境寫兩套。若還要判斷手勢方向與距離,也可以考慮成熟的表板函式庫,省去自己處理多指縮放、邊界取消等邊緣情況。