能力中的 API
Device Posture API(折叠设备)
发布于
navigator.devicePosture 属性提供 DevicePosture 对象,可读取当前生效的设备姿态并接收变化事件;规范定义的取值是 "continuous" 和 "folded"。
支持情况
链接到“支持情况”一节BCD 记录 Chrome 132 和 Samsung Internet 16.2 起支持这个 API,Chromium 衍生浏览器条目沿用 Chrome 数据;Firefox 与桌面 Safari 没有支持记录,iOS Safari 27 则需要开启 DevicePostureEnabled 偏好设置。
const posture = navigator.devicePosture.type;navigator.devicePosture.addEventListener('change', handlePostureChange);规范只在安全上下文的 Window 中暴露 navigator.devicePosture。
| 成员 | 类型 | 含义 |
|---|---|---|
type |
DevicePostureType |
返回文档当前生效的姿态,值为 "continuous" 或 "folded"。 |
change |
事件 | 生效姿态改变后,在 DevicePosture 对象上触发。 |
DevicePosture 接口继承自 EventTarget。devicePosture 属性带有 [SameObject],重复访问会返回同一个对象。
无。
以下示例都保留单栏布局作为回退。API 不可用或设备姿态不是折叠状态时,页面仍能正常显示。
在折叠与单栏布局间切换
链接到“在折叠与单栏布局间切换”一节下面的代码检测 API、应用当前姿态,并在 API 不可用时选择单栏 class。
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 时,下面的规则才会改变布局。
.workspace { display: block;}
@media (device-posture: folded) { .workspace { display: grid; grid-template-columns: 1fr 1fr; }}媒体特性不受支持或不匹配时,页面继续使用块布局。
另请参阅
链接到“另请参阅”一节规范
| 规范 | 状态 |
|---|---|
| DevicePosture interface | W3C 草案 |