廢話不多說,先上代碼
if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion',deviceMotionHandler, false);
}else{
console.log('不支持DeviceMotionEvent');
}
var speed = 20;//speed
var x = y = z = lastX = lastY = lastZ = 0;
function deviceMotionHandler(event) {
var acceleration =event.accelerationIncludingGravity;
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
if(Math.abs(x-lastX) > speed || Math.abs(y-lastY) > speed || Math.abs(z-lastZ) > speed) {
//簡單的搖一搖觸發(fā)代碼
console.log('搖一搖啊');
}
lastX = x;
lastY = y;
lastZ = z;
}
首先判斷瀏覽器是否支持window.DeviceMotionEvent,
DeviceMotionEvent為web開發(fā)者提供了關(guān)于設(shè)備的位置和方向改變的速度的信息。
如果支持則監(jiān)聽devicemotion事件。如果設(shè)備在X,Y,Z軸方向上有位移,那么回調(diào)函數(shù)中的參數(shù)event對象中就會反應(yīng)出來。

這里我們用到event對象中的accelerationIncludingGravity屬性,它提供了設(shè)備在X,Y,Z軸方向上帶重力的加速度的對象。
通過判斷前后兩次重力加速度差來判斷手機是否被搖了。
Math.abs(x-lastX) > speed || Math.abs(y-lastY) > speed || Math.abs(z-lastZ) > speed
只要x,y,z軸任意方向滿足條件就判定被搖