一. 简介
要实现h5检测手机摇一摇动作能够间接调用h5原生api。然而在我的实际中发现在ios
中限度条件比拟多,体验还是有些区别的。
二. 如何监听
调用Window: devicemotion event
即可实现监听。devicemotion
事件以固定的工夫距离触发,并批示设施过后在接管的减速物理力量。 它还提供无关旋转速率的信息(如果有)。
function handleMotionEvent(event) { var x = event.accelerationIncludingGravity.x; var y = event.accelerationIncludingGravity.y; var z = event.accelerationIncludingGravity.z; // Do something awesome.}window.addEventListener("devicemotion", handleMotionEvent, true);
三. 安卓机
安卓机上间接依照如上即可实现。
<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>测试摇一摇</title></head><body><div class="phone"> <div id="show">摇一摇</div></div></body><script>function handleMotionEvent(event) { document.getElementById('show').innerHTML = '摇动中'}if (window.DeviceMotionEvent) { window.addEventListener("devicemotion", handleMotionEvent, false);} else { alert("该浏览器不反对摇一摇性能");}</script></html>
四. iPhone
1. 限度
在ios
上限度有两条:
- h5必须是
https
协定的 - 必须用户点击受权才能够调用
devicemotion
2. 受权
function getPermission() { if ( typeof window.DeviceMotionEvent !== 'undefined' && typeof window.DeviceMotionEvent.requestPermission === 'function' ) { window.DeviceMotionEvent.requestPermission() .then(function(state) { if ('granted' === state) { //用户批准受权 } else { //用户回绝受权 alert('摇一摇须要受权设施静止权限,请重启利用后,再次进行受权!') } }) .catch(function(err) { alert('error: ' + err) }) }}
间接调用该函数申请受权会导致报错:
error: NotAllowedError: Requesting device orientation or motion access requires a user gesture to prompt
须要用户被动去申请受权,因而此处须要将调用放到比方一个按钮上,让用户去点击申请受权。
<button onclick="getPermission()">申请受权</button>
3. 全副代码
<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>测试摇一摇</title></head><body><div class="phone"> <button onclick="getPermission()">申请受权</button> <div id="show"></div></div></body><script>function handleMotionEvent(event) { document.getElementById('show').innerHTML = '摇动中'}function startListen() { if (window.DeviceMotionEvent) { window.addEventListener("devicemotion", handleMotionEvent, false); } else { alert("该浏览器不反对摇一摇性能"); }}function getPermission() { if ( typeof window.DeviceMotionEvent !== 'undefined' && typeof window.DeviceMotionEvent.requestPermission === 'function' ) { window.DeviceMotionEvent.requestPermission() .then(function(state) { if ('granted' === state) { //用户批准受权 startListen() } else { //用户回绝受权 alert('摇一摇须要受权设施静止权限,请重启利用后,再次进行受权!') } }) .catch(function(err) { alert('error: ' + err) }) }}</script></html>
五. 原文链接
Kuari's Blog