js实现震动
使用 navigator.vibrate API
现代浏览器支持通过 navigator.vibrate 方法触发设备震动。该方法接受一个参数,可以是数字(单次震动时长)或数组(震动模式交替)。

// 单次震动200毫秒
navigator.vibrate(200);
// 震动模式:震动200ms,暂停100ms,再震动300ms
navigator.vibrate([200, 100, 300]);
兼容性检查
调用前建议检查浏览器支持情况,避免在不支持的设备上报错:

if ('vibrate' in navigator) {
navigator.vibrate(200);
} else {
console.log('Vibration API not supported');
}
取消震动
通过传递 0 或空数组可以立即停止震动:
navigator.vibrate(0); // 停止震动
注意事项
- 用户交互要求:部分浏览器要求震动必须由用户交互(如点击事件)触发,不能在页面加载时自动执行。
- 移动端支持:主要适用于移动设备,桌面浏览器可能不支持或无效。
- 权限限制:某些浏览器可能需要用户授权震动权限。
封装实用函数
以下是一个封装好的震动函数,包含错误处理和回调:
function triggerVibration(pattern, onSuccess, onError) {
try {
if ('vibrate' in navigator) {
const success = navigator.vibrate(pattern);
if (success && typeof onSuccess === 'function') {
onSuccess();
} else if (!success && typeof onError === 'function') {
onError('Vibration failed');
}
} else {
throw new Error('API not supported');
}
} catch (err) {
if (typeof onError === 'function') {
onError(err.message);
}
}
}
// 使用示例
triggerVibration(
[100, 50, 100],
() => console.log('Vibrated successfully'),
(err) => console.error('Error:', err)
);






