IOS 上使用 devicemotion,deviceorientation 事件获取移动设备方向和动作数据时,不起效
原因: ios13+ 限制了该事件
必须在有用户点击才可拉起询问,询问同意才可以响应这两个事件
<button onclick="start()">start</button>
<script>
(function () { var script = document.createElement('script'); script.src="https://cdn.jsdelivr.net/npm/eruda"; document.body.appendChild(script); script.onload = function () { eruda.init() } })();
function start(){
if(!DeviceMotionEvent){
console.error('暂时不支持')
}else{
if(
DeviceMotionEvent.requestPermission
){
DeviceMotionEvent.requestPermission().then(permissionState => {
console.log(permissionState)
if (permissionState === 'granted') {
window.addEventListener('devicemotion', function(e) { console.log('devicemotion', e)}, true);
window.addEventListener('deviceorientation', function(e) { console.log('deviceorientation', e)}, true);
}
}).catch((err) => {
console.error(err);
});
}else{
window.addEventListener('devicemotion', function(e) { console.log('devicemotion', e)}, true);
window.addEventListener('deviceorientation', function(e) { console.log('deviceorientation', e)}, true);
}
}
}
</script>
demo
demo源码
|