| 事件 | 觸發時機 | 關鍵屬性 |
|---|---|---|
| `touchstart` | 手指剛接觸螢幕 | `touches`、`targetTouches`、`changedTouches` |
| `touchmove` | 手指在螢幕滑動(持續觸發) | 同 `touchstart`,`event.cancelable` 為 true |
| `touchend` | 手指離開螢幕 | `changedTouches`(離開的手指資訊) |
| `touchcancel` | 系統打斷觸控(來電、彈窗) | 同 `touchend`,務必配對清理狀態 |
{
identifier: Number, // 唯一 ID,追蹤同一手指
target: EventTarget, // 觸發元素
clientX, clientY, // 相對視窗
pageX, pageY, // 相對文檔(含滾動)
screenX, screenY, // 相對螢幕
radiusX, radiusY, // 橢圓半徑(壓力感應)
rotationAngle, // 旋轉角度
force: 0~1 // 壓力(需硬體支援)
}
const el = document.getElementById('draggable');
let startX, startY, initLeft, initTop;
el.addEventListener('touchstart', e => {
if (e.touches.length !== 1) return; // 單指操作
const t = e.touches[0];
startX = t.pageX; startY = t.pageY;
initLeft = el.offsetLeft; initTop = el.offsetTop;
el.style.position = 'absolute';
el.style.zIndex = 999;
}, { passive: true }); // 不阻塞滾動
el.addEventListener('touchmove', e => {
if (e.touches.length !== 1) return;
const t = e.touches[0];
const dx = t.pageX - startX;
const dy = t.pageY - startY;
el.style.left = (initLeft + dx) + 'px';
el.style.top = (initTop + dy) + 'px';
}, { passive: false }); // 需 preventDefault 防頁面滾動
el.addEventListener('touchend', e => {
// 可在此判斷是否超出邊界、吸附、觸發 click 等
}, { passive: true });
// 現代瀏覽器已移除 300ms 延遲,但仍需處理:
// 1. 同一元素同時綁 touchstart + click → touchend 後立即觸發 click,導致穿透
// 解法:touchend 時 e.preventDefault(),或用 pointer-events:none 延遲
// 2. CSS: touch-action: manipulation 禁用雙擊縮放,加速 click 觸發
button { touch-action: manipulation; }
// 滑動方向判斷
el.addEventListener('touchend', e => {
const t = e.changedTouches[0];
const dx = t.pageX - startX;
const dy = t.pageY - startY;
if (Math.abs(dx) > Math.abs(dy)) {
dx > 30 ? console.log('向右滑') : dx < -30 ? console.log('向左滑') : null;
} else {
dy > 30 ? console.log('向下滑') : dy < -30 ? console.log('向上滑') : null;
}
});
// 長按(500ms)
let pressTimer;
el.addEventListener('touchstart', () => pressTimer = setTimeout(() => console.log('長按'), 500));
el.addEventListener('touchend', () => clearTimeout(pressTimer));
el.addEventListener('touchmove', () => clearTimeout(pressTimer)); // 移動取消長按
// 雙指縮放(pinch)
el.addEventListener('touchmove', e => {
if (e.touches.length === 2) {
const [t1, t2] = e.touches;
const dist = Math.hypot(t1.pageX - t2.pageX, t1.pageY - t2.pageY);
// 對比上一幀 dist 計算 scale
}
}, { passive: true });
現代專案建議直接使用 `pointerdown`/`pointermove`/`pointerup`,自動處理多輸入裝置,無需分開寫 `mousedown` + `touchstart`。
el.addEventListener('pointerdown', e => {
if (e.pointerType === 'touch') { /* 觸控專屬邏輯 */ }
// 統一座標:e.clientX / e.clientY
});
觸控事件看似簡單,實則涉及瀏覽器滾動機制、事件傳遞、多指協同、效能優化等深層機制。掌握 `passive` 選項、邊界處理、手勢識別邏輯,並善用 `Pointer Events` 統一介面,才能打造媲美原生 App 的流暢觸控體驗。