废话不说直接上代码
<template>
<div class="guide" @click="shake" @touchmove.prevent>
</div>
</template>
<script @type="es6">
export default {
name: "guide",
created() {
//运动事件监听
if (window.DeviceMotionEvent) {
window.addEventListener("devicemotion", this.deviceMotionHandler, false);
}else{
alert("您的浏览器不支持DeviceOrientation");
}
},
data() {
return {
SHAKE_THRESHOLD: 4000,//速度要大于4000,证明用户是在快速摇手机
lastUpdate: 0,
x: 0,
y: 0,
z: 0,
lastX: 0,
lastY: 0,
lastZ: 0
//获取加速度信息
//通过监听上一步获取到的x, y, z 值在一定时间范围内的变化率,进行设备是否有进行晃动的判断。
//而为了防止正常移动的误判,需要给该变化率设置一个合适的临界值。
};
},
methods: {
shake(){
//do what you want to do
},
deviceMotionHandler(eventData) {
let acceleration = eventData.accelerationIncludingGravity;
let curTime = new Date().getTime();// 当前时间戳
if (curTime - this.lastUpdate > 100) {//手机抖动的时间要大于100ms,防止用户拿手机时,突然抖动而触发摇一摇功能
let diffTime = curTime - this.lastUpdate;
this.lastUpdate = curTime;
this.x = acceleration.x;// 表示x轴(西到东)上的加速度
this.y = acceleration.y;// 表示y轴(南到北)上的加速度
this.z = acceleration.z;// 表示z轴(下到上)上的加速度
let speed =
(Math.abs(
this.x + this.y + this.z - this.lastX - this.lastY - this.lastZ
) /
diffTime) *
10000;
if (speed > this.SHAKE_THRESHOLD) {//速度要大于4000,证明用户是在快速摇手机
window.removeEventListener(//移除运动事件监听
"devicemotion",
this.deviceMotionHandler,
false
);
this.shake();// 摇一摇要做的事情
}
this.lastX = this.x;
this.lastY = this.y;
this.lastZ = this.z;
}
}
}
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
</style>
网友评论