Html5监听手机摇一摇事件的实现

2020-04-24 19:04:16易采站长站整理

MDN地址:

https://developer.mozilla.org/zh-CN/docs/Web/API/DeviceMotionEvent/DeviceMotionEvent

下面为vue实现代码


<template>
<div id="Shake">
<van-popup v-model="show">
<div class="ad-box">
<span class="skip-ad" @click="hideAD">跳过广告({{time}})</span>
<img src="../../../../assets/img/shake/shake_ad.jpg" alt>
</div>
</van-popup>
<div class="shake-page">
<span class="cash-withdrawal-btn">提现</span>
<img
class="shake-img shake-horizontal"
:class="shake?'shake-horizontal-move':''"
src="../../../../assets/img/shake/shake.png"
alt="摇一摇"
@click="shakeImg"
>
</div>
<audio
style="display: none;"
:src="publicDir + '/static/audio/5018.mp3'"
ref="musicBox"
preload="preload"
controls
></audio>
</div>
</template>

<script>
import { setTimeout } from "timers";
import config from "../../../../utils/config.js";
export default {
name: "Shake",
data() {
return {
time: 5,
show: true,
shake: false,
SHAKE_THRESHOLD: 3000,
last_update: 0,
last_x: 0,
last_y: 0,
last_z: 0,
publicDir: config.publicDir
};
},
mounted() {
this.init();
this.countDown();
},
methods: {
// 广告倒计时
countDown() {
setTimeout(() => {
if (this.time < 1) {
this.show = false;
} else {
this.time--;
this.countDown();
}
}, 1000);
},
// 显示广告
showPopup() {
this.show = true;
},
// 隐藏广告
hideAD() {
this.show = false;
},
// 开启图片摇动效果
shakeImg() {
if (!this.show) {
this.shake = true;
this.$refs.musicBox.play();
window.removeEventListener("devicemotion", this.deviceMotionHandler, false);
setTimeout(() => {
this.shake = false;
this.routerPush("/RedBag");
}, 2000);
}
},
// 路由跳转
routerPush(path, query) {
this.$router.push({
path,
query
});
},
// 初始化摇一摇,添加摇动监听
init() {
this.last_update = new Date().getTime();
if (window.DeviceMotionEvent) {
window.addEventListener(
"devicemotion",
this.deviceMotionHandler,
false
);
} else {
alert("not support mobile event");
}
},
// 摇一摇事件回调函数
deviceMotionHandler(eventData) {
var acceleration = eventData.accelerationIncludingGravity;
var curTime = new Date().getTime();
if (curTime - this.last_update > 100) {
var diffTime = curTime - this.last_update;