1.需要申请权限
window.DeviceOrientationEvent.requestPermission()
.then(state => {
if (state === "granted") { //允许
alert("用户允许")
} else if (state === "denied") { //拒绝
alert("用户拒绝")
} else if (state === "prompt") {
alert("用户干了啥")
}
})
2.requestPermission方法的”首次“调用 需要 由用户交互触发(目前发现 click,touchend事件可以)
2.1 先说下 ”首次“的含义。指的是用户 完全退出app(而不是 app切换到后台运行) 后再次打开为首次。用户在首次进入后 如果页面需要陀螺仪权限,需要用户交互才能触发requestPermission方法。之后系统会记录 用户对本网址的授权信息,不退出app的情况下就不需要重复申请本权限了,本记录信息会一直保留 直到完全退出app。
2.2 非首次调用的话 则不需要用户交互 触发,我们在页面初始化时调用来拿到 用户的 授权状态 进而做一些处理。
2.3 如果首次调用 不是由 用户触发,比如 页面初始化时 调用,则此方法的promis会返回reject状态。
3.需要注意,使用陀螺仪 需要https协议,且一经用户授权/禁止,系统会保留用户授权状态,不再重复系统弹框,直到完全退出app。
4.摇一摇列子
<!DOCTYPE html>
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<meta http-equiv="content-security-policy">
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/jquery.min.js"></script>
</head>
<body id="body">
<button>点击</button>
</body>
<style>
button {
width: 80%;
height: 60px;
margin-top: 20%;
font-size: 18px;
}
</style>
<script>
$(function() {
$('button').on('touchend', function(e){
requestT()
});
})
function requestT() {
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf("like mac os x") > 0) {
var reg = /os [\d._]*/gi;
var verinfo = ua.match(reg);
var version = (verinfo + "").replace(/[^0-9|_.]/ig, "").replace(/_/ig, ".");
var arr = version.split(".");
alert(arr[0] + "." + arr[1] + "." + arr[2])
if (arr[0] > 12 && arr[1] > 2) { //对13.3以后的版本处理,包括13.3,
if (typeof(DeviceMotionEvent) !== 'undefined' && typeof(DeviceMotionEvent.requestPermission) === 'function') {
window.DeviceOrientationEvent.requestPermission()
.then(state => {
if (state === "granted") { //允许
alert("用户允许")
// 监听传感器运动事件
if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion', deviceMotionHandler );
} else {
alert('本设备不支持devicemotion事件');
}
} else if (state === "denied") { //拒绝
alert("用户拒绝")
} else if (state === "prompt") {
alert("用户干了啥")
}
})
.catch(console.error)
} else {
alert('DeviceMotionEvent is not defined');
}
} else {
alert("旧版")
// 监听传感器运动事件
if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion', deviceMotionHandler);
} else {
alert('本设备不支持devicemotion事件');
}
}
}
}
// 定义一个摇动的阈值:为了防止正常移动的误判,需要给该变化率设置一个合适的临界值
var shakeThreshold = 500;
// 记录上一次摇动的时间
var lastUpdate = 0;
// 定义x、y、z记录三个轴的数据以及上一次触发的数据
var x, y, z, lastX, lastY, lastZ;
// 运动传感器处理
function deviceMotionHandler(e) {
// 获取含重力的加速度
var acceleration = e.accelerationIncludingGravity;
var curTime = Date.now();
// 100毫秒进行一次位置判断
if ((curTime - lastUpdate) > 100) {
var diffTime = curTime - lastUpdate;
lastUpdate = curTime;
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
var speed = Math.abs(x + y + z - lastX - lastY - lastZ) / diffTime * 10000;
// 前后x, y, z间的差值的绝对值和时间比率超过了预设的阈值,则判断设备进行了摇晃操作
if (speed > shakeThreshold) {
// doSomething();
alert('摇摆')
}
lastX = x;
lastY = y;
lastZ = z;
}
}
</script>
</html>