# 记录一次移动端开发摇一摇功能所踩的坑

2018/06/07 19:29

``````然后就封装方法，去监听'devicemotion'函数，```
``````

`````` function handler(e) {

var current = e.accelerationIncludingGravity;
var currentTime;
var timeDifference;
var deltaX = 0;
var deltaY = 0;
var deltaZ = 0;

//记录上一次设备在x,y,z方向上的加速度
if ((lastX === null) && (lastY === null) && (lastZ === null)) {
lastX = current.x;
lastY = current.y;
lastZ = current.z;
return;
}

//得到两次移动各个方向上的加速度绝对差距
deltaX = Math.abs(lastX - current.x);
deltaY = Math.abs(lastY - current.y);
deltaZ = Math.abs(lastZ - current.z);
//当差距大于设定的阀值并且时间间隔大于指定阀值时，触发摇一摇逻辑
if (((deltaX > threshold) && (deltaY > threshold)) || ((deltaX > threshold) && (deltaZ > threshold)) || ((deltaY > threshold) && (deltaZ > threshold))) {
currentTime = new Date;
timeDifference = currentTime.getTime() - lastTime.getTime();

//时间间隔
if (timeDifference > timeout && drawStatus) {
//触发摇一摇事件
dealShake();
lastTime = new Date;
}
}

lastX = current.x;
lastY = current.y;
lastZ = current.z;
}

function dealShake() {
if (isShaking) return;  // 判断状态是否为进行时，否则不触发
isShaking = !0;  // 初始化状态
drawFun();
setTimeout(function () {
\$("#shakemusic")[0].pause();
isShaking = !1;
}, 1500);
}
``````

0
4 收藏

0 评论
4 收藏
0