ScreenOrientation API 并非所有浏览器都支持,iOS Safari 完全不支持(截至 iOS 17.5),Android Chrome、Firefox、Edge 基本可用;调用前须用 "orientation" in screen 判断存在性,否则报 TypeError;screen.orientation.type 返回方向状态字符串,angle 返回 0/90/180/270 度数值;应使用 screen.orientation.addEventListener("change", handler) 监听变化,而非废弃的 orientationchange 事件;lock() 需用户手势触发,否则抛 NotAllowedError,且需处理 PermissionDenied;最终方向判断应以 window.innerWidth > window.innerHeight 为 fallback。
不是所有浏览器都支持 screen.orientation,尤其 iOS Safari 完全不支持该 API(截至 iOS 17.5),Android Chrome、Firefox、Edge(Chromium 内核)基本可用。调用前必须做存在性判断,否则直接报 TypeError: Cannot read properties of undefined。
"orientation" in screen 或 typeof screen.orientation !== "undefined"
resize 或 orientationchange 事件,也无法通过 screen.orientation.type 获取真实方向,只能靠 window.innerWidth / window.innerHeight 推断undefined 或只读属性异常screen.orientation.type 返回字符串,表示当前锁定/自然方向状态;screen.orientation.angle 是数值,单位为度,反映设备物理旋转角度。二者不总同步——比如用户未锁定方向但横屏手持,type 可能是 "landscape-primary",angle 是 90 或 270。
type 常见值:"portrait-primary"、"portrait-secondary"、"landscape-primary"、"landscape-secondary"
angle 只能是 0、90、180、270 四个值,对应竖屏正放、横屏左转、竖屏倒置、横屏右转screen.orientation.type 在页面刚加载时可能尚未就绪,建议在 DOMContentLoaded 后读取,或监听 orientationchange 事件再取推荐用 screen.orientation.addEventListener("change", handler),而不是过时的 orientationchange 全局事件(后者已被废弃,且在多数现代浏览器中不触发)。
orientationchange 是早期 iOS 提出的非标准事件,仅在部分旧版 Safari 中有效,现在基本失效screen.orientation.addEventListener("change", ...) 是标准方式,兼容 Chrome 58+、Firefox 63+、Edge 79+screen.orientation.type 和 screen.orientation.angle,不要依赖闭包缓存值if ("orientation" in screen) {
const handler = () => {
console.log("当前方向:", screen.orientation.type);
console.log("旋转角度:", screen.orientation.angle);
};
screen.orientation.addEventListener("change", handler);
// 初始值也手动触发一次
handler();
}
screen.orientation.lock() 是受权限和上下文严格限制的异步操作,失败非常常见,不能假设它一定成功。

click、touchend)触发的回调中首次调用,否则抛 NotAllowedError
PermissionDenied(但目前 Chrome 不弹明确提示,只静默失败)document.documentElement.requestFullscreen() 后)才允许锁方向;普通页面中调用常被忽略change 事件捕获该状态回退真正稳定可控的方向感知,仍应以 window.innerWidth > window.innerHeight 为 fallback 主逻辑,screen.orientation 仅作增强补充。