# Device Posture API（折叠设备）

> navigator.devicePosture 如何提供 continuous 与 folded 姿态、报告变化，并在不可用时回退到单栏布局。

`navigator.devicePosture` 属性提供 `DevicePosture` 对象，可读取当前生效的设备姿态并接收变化事件；规范定义的取值是 `"continuous"` 和 `"folded"`。

## 支持情况

BCD 记录 Chrome 132 和 Samsung Internet 16.2 起支持这个 API，Chromium 衍生浏览器条目沿用 Chrome 数据；Firefox 与桌面 Safari 没有支持记录，iOS Safari 27 则需要开启 `DevicePostureEnabled` 偏好设置。

## 语法

```js
const posture = navigator.devicePosture.type;
navigator.devicePosture.addEventListener('change', handlePostureChange);
```

规范只在安全上下文的 `Window` 中暴露 `navigator.devicePosture`。

## 成员

| 成员 | 类型 | 含义 |
|---|---|---|
| `type` | `DevicePostureType` | 返回文档当前生效的姿态，值为 `"continuous"` 或 `"folded"`。 |
| `change` | 事件 | 生效姿态改变后，在 `DevicePosture` 对象上触发。 |

`DevicePosture` 接口继承自 `EventTarget`。`devicePosture` 属性带有 `[SameObject]`，重复访问会返回同一个对象。

## 异常

无。

:::caution
文档隐藏时，设备姿态变化步骤会停止。规范指出，文档再次可见后会收到变化事件；因此在隐藏期间读取到的姿态可能尚未更新（[Device Posture change](https://w3c.github.io/device-posture/#device-posture-change)）。
:::

## 示例

以下示例都保留单栏布局作为回退。API 不可用或设备姿态不是折叠状态时，页面仍能正常显示。

### 在折叠与单栏布局间切换

下面的代码检测 API、应用当前姿态，并在 API 不可用时选择单栏 class。

```js
function applyPosture(type) {
  document.documentElement.classList.toggle('is-folded', type === 'folded');
  document.documentElement.classList.toggle('is-single-pane', type !== 'folded');
}

if ('devicePosture' in navigator) {
  applyPosture(navigator.devicePosture.type);
  navigator.devicePosture.addEventListener('change', () => {
    applyPosture(navigator.devicePosture.type);
  });
} else {
  applyPosture('continuous');
}
```

回退分支选择的单栏布局也用于规范定义的 `"continuous"` 值。它不会推断物理设备能否折叠。

### 使用媒体查询适配

规范还定义了 `device-posture` 媒体特性。只有用户代理报告 `folded` 时，下面的规则才会改变布局。

```css
.workspace {
  display: block;
}

@media (device-posture: folded) {
  .workspace {
    display: grid;
    grid-template-columns: 1fr 1fr;
  }
}
```

媒体特性不受支持或不匹配时，页面继续使用块布局。

## 另请参阅

- [Screen Orientation API](/zh/reference/capabilities/screen-orientation-api/)
- [orientation manifest 成员](/zh/reference/manifest/orientation/)
- [Device Posture API 规范（W3C）](https://w3c.github.io/device-posture/)
- [DevicePosture（MDN）](https://developer.mozilla.org/en-US/docs/Web/API/DevicePosture)