h5实现摇一摇
实现摇一摇功能的H5方案
检测设备加速度
使用HTML5的DeviceMotion API监听设备加速度变化。在JavaScript中通过window.addEventListener('devicemotion', callback)实现。回调函数中可获取加速度数据(event.accelerationIncludingGravity),包含x、y、z三轴的重力加速度值(单位:m/s²)。
let shakeThreshold = 15; // 摇动阈值(根据灵敏度调整)
let lastTime = 0;
let lastX = null, lastY = null, lastZ = null;
window.addEventListener('devicemotion', (event) => {
const { x, y, z } = event.accelerationIncludingGravity;
const currentTime = Date.now();
if ((currentTime - lastTime) > 100) { // 限制检测频率
const speed = Math.abs(x + y + z - lastX - lastY - lastZ) / (currentTime - lastTime) * 10000;
if (speed > shakeThreshold) {
// 触发摇动事件
handleShake();
}
lastX = x; lastY = y; lastZ = z;
lastTime = currentTime;
}
});
处理摇动事件
当检测到有效摇动时,执行自定义逻辑(如显示动画、调用接口等)。建议添加防抖处理避免重复触发。
function handleShake() {
console.log('Shake detected!');
// 示例:显示反馈动画
document.getElementById('shake-feedback').classList.add('active');
setTimeout(() => {
document.getElementById('shake-feedback').classList.remove('active');
}, 1000);
// 实际业务逻辑(如抽奖接口调用)
// fetch('/api/shake').then(...);
}
用户授权处理
iOS 13+和部分安卓系统需要用户手势交互后才能获取传感器数据。需在按钮点击事件中请求权限:
document.getElementById('shake-btn').addEventListener('click', () => {
if (typeof DeviceMotionEvent.requestPermission === 'function') {
DeviceMotionEvent.requestPermission()
.then(permissionState => {
if (permissionState === 'granted') {
window.addEventListener('devicemotion', shakeHandler);
}
});
}
});
兼容性优化
-
添加非移动端提示:
if (!('ondevicemotion' in window)) { alert('请使用手机访问此页面'); } -
低版本iOS降级方案:
/* 通过CSS动画模拟摇动效果 */ @keyframes shake { 0%, 100% { transform: translateX(0); } 20%, 60% { transform: translateX(-10px); } 40%, 80% { transform: translateX(10px); } }
.shake-fallback { animation: shake 0.5s; }
#### 注意事项
1. 生产环境建议使用库(如shake.js)简化实现
2. 阈值(shakeThreshold)需通过真机测试调整,通常范围10-30
3. 部分浏览器需要HTTPS环境才能使用传感器API
4. 考虑用户长时间未摇动时的超时处理逻辑
