利用 DeviceMotionEvent 實現「搖一搖」互動是行動網頁常見需求,但直接使用原始事件易誤觸、重複觸發、動畫衝突。本文從基礎監聽進階到「動畫執行鎖」與「閾值自適應」完整方案,提供可直接投入生產的封裝代碼。
if (window.DeviceMotionEvent) {
const SHAKE_THRESHOLD = 25; // 經驗值,視專案調整
let lastX = 0, lastY = 0, lastZ = 0;
window.addEventListener('devicemotion', (e) => {
const { x, y, z } = e.accelerationIncludingGravity;
const deltaX = Math.abs(x - lastX);
const deltaY = Math.abs(y - lastY);
// const deltaZ = Math.abs(z - lastZ); // Z 軸通常噪聲大,建議不納入
if (deltaX > SHAKE_THRESHOLD || deltaY > SHAKE_THRESHOLD) {
triggerShakeAction(); // 你的業務邏輯
}
lastX = x; lastY = y; lastZ = z;
}, { passive: true }); // passive 提升滾動效能
}
當搖一搖觸發動畫(如抽獎轉盤、骰子滾動)時,必須確保動畫播放完畢前不再響應新的搖動事件。
let isAnimating = false; // 鎖標誌
function triggerShakeAction() {
if (isAnimating) return; // 動畫中忽略新觸發
isAnimating = true;
// 例:jQuery 動畫
$('.shake-target').animate({ left: 0, opacity: 1 }, 700, () => {
isAnimating = false; // 動畫結束釋放鎖
});
// 或 Promise 版本(現代寫法)
// await animateShake(); isAnimating = false;
}
if (window.DeviceMotionEvent) {
const SHAKE_THRESHOLD = 25;
let lastX = 0, lastY = 0, lastZ = 0;
window.addEventListener('devicemotion', (e) => {
const { x, y, z } = e.accelerationIncludingGravity;
if (Math.abs(x - lastX) > SHAKE_THRESHOLD || Math.abs(y - lastY) > SHAKE_THRESHOLD) {
triggerShakeAction();
}
lastX = x; lastY = y; lastZ = z;
}, { passive: true });
}
navigator.userAgent)或首次校準階段統計靜止時的噪聲標準差,動態調整 SHAKE_THRESHOLD。setTimeout(() => shakeCooldown = false, 1500)),避免手部回彈產生的二次峰值。DeviceMotionEvent,請引導使用者先互動。DeviceMotionEvent.requestPermission(),建議封裝跨平台權限請求函式。{passive:true} 避免阻塞主執行緒;若無需 Z 軸可不讀取以減少物件建立開銷。window.dispatchEvent(new DeviceMotionEvent('devicemotion', {accelerationIncludingGravity:{x:30,y:0,z:9.8}})) 模擬搖動進行自動化測試。// shake-detector.js
export class ShakeDetector {
constructor(options = {}) {
this.threshold = options.threshold || 25;
this.cooldown = options.cooldown || 1000;
this.onShake = options.onShake || (() => {});
this._last = {x:0,y:0,z:0};
this._cooling = false;
this._boundHandler = this._handle.bind(this);
}
start() {
if (!window.DeviceMotionEvent) return console.warn('DeviceMotionEvent not supported');
window.addEventListener('devicemotion', this._boundHandler, {passive:true});
}
stop() { window.removeEventListener('devicemotion', this._boundHandler); }
_handle(e) {
if (this._cooling) return;
const {x,y,z} = e.accelerationIncludingGravity;
const dx = Math.abs(x - this._last.x), dy = Math.abs(y - this._last.y);
this._last = {x,y,z};
if (dx > this.threshold || dy > this.threshold) {
this._cooling = true;
this.onShake();
setTimeout(() => this._cooling = false, this.cooldown);
}
}
}
// 使用範例
import {ShakeDetector} from './shake-detector.js';
const detector = new ShakeDetector({
threshold: 20,
cooldown: 1500,
onShake: () => { console.log('搖一搖觸發!'); /* 播放動畫、呼叫 API */ }
});
detector.start();
// 頁面卸載時 detector.stop() 釋放資源
採用模組化、可配置、帶生命週期管理的封裝,能讓「搖一搖」功能在複雜專案中穩定、可測試、易維護。