我试图通过 deviceorientation 获取 alpha、beta 和 gamma 坐标事件。
我的代码:
window.addEventListener('deviceorientation', function(event) {
alert(event.alpha + ' : ' + event.beta + ' : ' + event.gamma);
});
JS fiddle :https://jsfiddle.net/myL17nzt/
这对于在设备移动时不断抓取坐标非常有用,但我想只抓取页面加载时的坐标而不是让它监听移动。我尝试将 window.addEventListener 更改为 window.onload,但这并没有成功。
有什么想法可以实现这一点吗?
谢谢!
最佳答案
最好让监听器自行删除。
function deviceOrientation(event) {
alert(event.alpha + ' : ' + event.beta + ' : ' + event.gamma);
window.removeEventListener('deviceorientation', deviceOrientation);
}
window.addEventListener('deviceorientation', deviceOrientation);
这样,您就不会因为您不关心的事件而调用它。一些库有一个名为 once
的函数,它会在第一次事件发生后删除事件监听器。
关于javascript - 在页面加载时使用设备方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33468368/