我目前正在开发的应用程序需要知道设备的方向,因此我使用此代码来检测orientationchange 事件:
window.addEventListener('orientationchange', function(){
theApp.orientationChange();
});
和这个属性来获得实际的方向值:
window.orientation
问题:在 2 种横向模式之间切换时,不会触发任何事件,方向分别保持在错误的 90 度或 -90 度。
我正在 2 台运行 2.3.5 和 4.4.4 的 Android 设备上进行测试,它们都显示相同的行为。
所以,问题是:
澄清
我希望我的应用程序显示从用户位置到目标地理位置的方向。
为此,我需要 2 个不同的方向信息:
要获取指南针,使用此插件:
org.apache.cordova.device-orientation 0.3.10 "Device Orientation"
我用
navigator.compass.watchHeading
获取标题更新 - 这部分正在工作。
要使箭头元素指向目标位置,应用程序不仅需要知道指南针的方向,还需要知道屏幕方向(window.orientation 属性中的 0、90、-90 和 180 度值)。
但是这个 window.orientation 属性在经过测试的 Android 设备上是错误的,当直接将设备方向从横向 1 更改为横向 2 时,而不是通过纵向模式。此外,在这种情况下不会触发orientationchange 事件。
IOS 示例代码(顺便说一句:示例中没有特定于 IOS 的内容,代码应该在每个 WebView 中运行)KRIZTE 所引用的依赖于正确的 window.orientation 值。提到的问题(延迟初始更新)不是我的代码的问题。
(测试-)用于检查 window.orientation 的代码:
setInterval(function(){
console.log('WO ' + window.orientation);
}, 1000);
等待orientationchange 事件:
window.addEventListener('orientationchange', function(){
console.log('window.orientation : ' + window.orientation);
});
注释日志:
[starting app]
[check function returns correct value:]
"WO 0"
...
[change device orientation to landscape 1]
[got orientationchanged event, value is correct]
"window.orientation : 90"
[check function returns correct value:]
"WO 90"
...
[change device orientation back to portrait]
[got orientationchanged event, value is correct]
"window.orientation : 0"
[check function returns correct value:]
"WO 0"
...
[change device orientation to landscape 2]
[got orientationchanged event, value is correct]
"window.orientation : -90"
[check function returns correct value:]
"WO -90"
...
[change device orientation to landscape 1]
... < Problem 1: no orientationchanged event
"WO -90" < Problem 2: wrong window.orientation value, value should be +90 deg
...
最佳答案
var orientation = window.orientation % 180 === 0 ? 'portrait' : 'landscape'
关于 Cordova 检测方向变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28283061/