You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测设备左横屏、右横屏等四种屏幕旋转方向?

四向屏幕旋转方向区分方案(兼容最新规范)

目前你查到的已弃用方法多为旧的非标准window.orientation相关接口,现在主流场景都可以通过标准API直接获取四类方向值,不需要依赖废弃属性,具体实现如下:


各场景实现方案

1. Web端实现

使用W3C标准ScreenOrientation接口,调用window.screen.orientation.type可直接返回你需要的四类方向枚举:

  • portrait-primary:对应 portrait right(默认竖屏,设备顶部朝上)
  • portrait-secondary:对应 portrait left(倒置竖屏,设备顶部朝下)
  • landscape-primary:对应 landscape right(右侧横屏,设备右侧朝上)
  • landscape-secondary:对应 landscape left(左侧横屏,设备左侧朝上)

最简监听代码示例:

// 初始化获取当前方向
let currentOrientation = window.screen.orientation.type;

// 监听方向变化
window.screen.orientation.addEventListener('change', () => {
  currentOrientation = window.screen.orientation.type;
  switch(currentOrientation) {
    case 'portrait-primary':
      // 执行默认竖屏对应逻辑
      break;
    case 'portrait-secondary':
      // 执行倒置竖屏对应逻辑
      break;
    case 'landscape-primary':
      // 执行右侧横屏对应逻辑
      break;
    case 'landscape-secondary':
      // 执行左侧横屏对应逻辑
      break;
  }
});

注意:该API兼容Chrome 38+、Safari 16.4+,覆盖绝大多数主流移动设备;部分移动端浏览器需要页面申请全屏权限后才能拿到完整的方向值,普通页面如果被系统强制锁定方向,返回值会以锁定后的方向为准。

2. 安卓原生实现

通过Display.getRotation()方法获取旋转角度即可对应四类方向:

  • 0°(Surface.ROTATION_0):默认竖屏(portrait right)
  • 90°(Surface.ROTATION_90):左侧横屏(landscape left)
  • 180°(Surface.ROTATION_180):倒置竖屏(portrait left)
  • 270°(Surface.ROTATION_270):右侧横屏(landscape right)

示例代码:

val display = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
    display
} else {
    windowManager.defaultDisplay
}
val rotation = display?.rotation ?: 0
when(rotation) {
    Surface.ROTATION_0 -> // 执行默认竖屏逻辑
    Surface.ROTATION_90 -> // 执行左侧横屏逻辑
    Surface.ROTATION_180 -> // 执行倒置竖屏逻辑
    Surface.ROTATION_270 -> // 执行右侧横屏逻辑
}

3. iOS原生实现

通过UIDevice.orientation属性直接获取对应枚举值即可:

  • UIDeviceOrientationPortrait:默认竖屏(portrait right)
  • UIDeviceOrientationPortraitUpsideDown:倒置竖屏(portrait left)
  • UIDeviceOrientationLandscapeLeft:左侧横屏(landscape left,设备左侧朝上)
  • UIDeviceOrientationLandscapeRight:右侧横屏(landscape right,设备右侧朝上)

注意:iOS部分机型默认禁用竖屏倒置权限,需要在项目配置中打开对应方向支持才能拿到portrait-secondary的返回值。


内容的提问来源于stack exchange,提问作者barryalan2633

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 12:45:02