本文提供一份可直接複製執行的「搖一搖」完整範例,包含裝置支援度檢測、參數調整說明與 UI 回饋,依賴 jQuery。
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div id="yaoyiyaono" style="display:none;font-size:20px;margin:10px;line-height:35px;">
不支援搖一搖:
1. 請使用手機瀏覽器
2. Android 請用 Chrome/UC 等第三方瀏覽器
3. 否則請更換支援裝置
</div>
<div id="yaoyiyaoyes" style="display:none;font-size:20px;margin:10px;line-height:50px;">
搖一搖試試,或許有驚喜!</div>
<div id="yaoyiyaoresult" style="display:none;font-size:20px;margin:10px;line-height:50px;"></div>
<script>
// 參數設定
const SHAKE_THRESHOLD = 3000; // 閾值,視測試調整
let lastUpdate = 0, lastX=0, lastY=0, lastZ=0, count=0;
function init() {
if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion', deviceMotionHandler, false);
$('#yaoyiyaoyes').show();
} else {
$('#yaoyiyaono').show();
}
}
function deviceMotionHandler(event) {
const acc = event.accelerationIncludingGravity;
const now = Date.now();
const diff = now - lastUpdate;
if (diff > 100) { // 100ms 取樣間隔
lastUpdate = now;
const speed = Math.abs(acc.x + acc.y + acc.z - lastX - lastY - lastZ) / diff * 10000;
if (speed > SHAKE_THRESHOLD) {
count++;
$('#yaoyiyaoyes').hide();
$('#yaoyiyaoresult').show().html(`搖你妹!第 ${count} 個了!`);
}
lastX = acc.x; lastY = acc.y; lastZ = acc.z;
}
}
$(document).ready(init);
</script>
| 參數 | 預設值 | 調整建議 |
|---|---|---|
| SHAKE_THRESHOLD | 3000 | 越大越難觸發;實機測試調整,建議 2000~5000 |
| 取樣間隔 | 100ms | 太短易誤觸,太長反應慢;50~200ms 之間 |
| 放大係數 | 10000 | 配合閾值調整,維持 speed 數值好判斷 |
觸發後可執行:抽獎轉盤、換頁導向、播放音效、發送 AJAX 請求、顯示優惠碼等。
此範例已整理為可直接部署的單檔版,適合快速整合至行銷活動頁面。