!!! 注意:在https协议下才能 获取权限
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<button onclick="clickMe()">获取权限</button>
<p id="z">z轴</p>
<p id="x">x轴</p>
<p id="y">y轴</p>
</div>
<script>
var z = document.getElementById('z')
var x = document.getElementById('x')
var y = document.getElementById('y')
function clickMe() {
DeviceOrientationEvent.requestPermission().then(res => {
console.log('res', res);
if (res === 'granted') {
console.log('允许了');
window.addEventListener('deviceorientation', function (event) {
z.innerText = 'z轴' + event.alpha
x.innerText = 'x轴' + event.beta
y.innerText = 'y轴' + event.gamma
});
} else {
alert('没能获取权限,无法正常操作,请重新打开应用准许本次操作,方可正常操作')
}
}).catch(err => {
console.log('err', err);
})
}
</script>
</body>
</html>