uni-app uni.onWindowResize在H5 ios端返回的值deviceOrientation是错误的
uni-app uni.onWindowResize在H5 ios端返回的值deviceOrientation是错误的
开发环境 | 版本号 | 项目创建方式 |
---|---|---|
Windows | Windows 11 | HBuilderX |
25987.1000 | ||
Windows Feature Experience Pack 1000.25987.1000.0 | ||
HBuilderX | 3.96 |
## 示例代码:
```javascript
this.windowResize = (res) => {
this.landscapeScreen = res.deviceOrientation == 'landscape'
}
uni.onWindowResize(this.windowResize)
操作步骤:
this.windowResize = (res) => {
this.landscapeScreen = res.deviceOrientation == 'landscape'
//ios横屏等于false(portrait)
}
uni.onWindowResize(this.windowResize)
预期结果:
this.windowResize = (res) => {
this.landscapeScreen = res.deviceOrientation == 'landscape'
//ios横屏等于true(landscape)
}
uni.onWindowResize(this.windowResize)
实际结果:
this.windowResize = (res) => {
this.landscapeScreen = res.deviceOrientation == 'landscape'
//ios横屏等于false(portrait)
}
uni.onWindowResize(this.windowResize)
bug描述:
this.windowResize = (res) => {
this.landscapeScreen = res.deviceOrientation == 'landscape'
}
uni.onWindowResize(this.windowResize)
this.landscapeScreen如果处于横屏时应该是true,但是在ios端是false,测试了一下在电脑和安卓看是正常的当横屏deviceOrientation 等于"landscape",但是在ios横屏返回的"portrait",竖屏返回的是 "landscape",就是完全反过来了
在 uni-app
中,uni.onWindowResize
是一个用于监听窗口大小变化的 API。然而,在某些情况下,特别是在 H5 的 iOS 端,deviceOrientation
的返回值可能会出现错误。这可能是由于 iOS 浏览器在处理设备方向变化时的行为与预期不一致。
可能的原因
- iOS 浏览器的限制:iOS 的 Safari 浏览器在处理设备方向变化时,可能会有一些限制或延迟,导致
deviceOrientation
的值不准确。 - 事件触发时机:
uni.onWindowResize
可能在某些情况下没有正确捕获到设备方向的变化,尤其是在快速旋转设备时。 - 兼容性问题:
uni-app
的 H5 端在不同浏览器和设备上的兼容性可能存在差异,导致deviceOrientation
的值不准确。
解决方案
-
使用原生 JavaScript 监听设备方向: 你可以尝试使用原生的 JavaScript 来监听设备方向的变化,而不是依赖
uni.onWindowResize
。例如:window.addEventListener('orientationchange', () => { const orientation = window.orientation; console.log('Device orientation:', orientation); // 根据 orientation 的值处理逻辑 });
window.orientation
返回的值可以是0
、90
、-90
或180
,分别表示不同的设备方向。 -
使用
window.innerWidth
和window.innerHeight
: 如果你主要关心的是窗口大小的变化,而不是设备方向,可以直接使用window.innerWidth
和window.innerHeight
来获取窗口的宽度和高度,并根据这些值来判断设备的方向。window.addEventListener('resize', () => { const width = window.innerWidth; const height = window.innerHeight; console.log('Window size:', width, height); // 根据 width 和 height 判断设备方向 });
-
使用
uni.getSystemInfo
: 你可以使用uni.getSystemInfo
来获取设备的系统信息,包括屏幕的宽度和高度,然后根据这些信息来判断设备的方向。uni.getSystemInfo({ success: (res) => { const screenWidth = res.screenWidth; const screenHeight = res.screenHeight; console.log('Screen size:', screenWidth, screenHeight); // 根据 screenWidth 和 screenHeight 判断设备方向 } });
-
处理延迟问题: 如果
deviceOrientation
的值在设备旋转后没有立即更新,你可以设置一个延迟来处理这个问题。例如,在orientationchange
事件触发后,延迟一段时间再获取deviceOrientation
的值。window.addEventListener('orientationchange', () => { setTimeout(() => { const orientation = window.orientation; console.log('Device orientation:', orientation); // 根据 orientation 的值处理逻辑 }, 300); // 延迟 300 毫秒 });