HTML5如何借助ScreenOrientation取屏幕方向数据_HTML5屏向取数法【集锦】

16次阅读

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。

HTML5如何借助ScreenOrientation取屏幕方向数据_HTML5屏向取数法【集锦】

ScreenOrientation API 是否可用,先看浏览器支持情况

不是所有浏览器都支持 screen.orientation,尤其 ios safari 完全不支持该 API(截至 ios 17.5),android chromefirefoxedge(Chromium 内核)基本可用。调用前必须做存在性判断,否则直接报 TypeError: Cannot read properties of undefined

  • 检查方式:用 "orientation" in screentypeof screen.orientation !== "undefined"
  • iOS 上即使监听 resizeorientationchange 事件,也无法通过 screen.orientation.type 获取真实方向,只能靠 window.innerWidth / window.innerHeight 推断
  • 部分 Android webview(如旧版微信 X5 内核)可能返回 undefined 或只读属性异常

获取当前屏幕方向类型:type 和 angle 的区别与取值逻辑

screen.orientation.type 返回字符串,表示当前锁定/自然方向状态;screen.orientation.angle 是数值,单位为度,反映设备物理旋转角度。二者不总同步——比如用户未锁定方向但横屏手持,type 可能是 "landscape-primary"angle90270

  • type 常见值:"portrait-primary""portrait-secondary""landscape-primary""landscape-secondary"
  • angle 只能是 090180270 四个值,对应竖屏正放、横屏左转、竖屏倒置、横屏右转
  • 注意:screen.orientation.type 在页面刚加载时可能尚未就绪,建议在 DOMContentLoaded 后读取,或监听 orientationchange 事件再取

监听方向变化:用 orientationchange 还是 addEventListener(“change”)?

推荐用 screen.orientation.addEventListener("change", handler),而不是过时的 orientationchange 全局事件(后者已被废弃,且在多数现代浏览器中不触发)。

  • orientationchange 是早期 iOS 提出的非标准事件,仅在部分旧版 Safari 中有效,现在基本失效
  • screen.orientation.addEventListener("change", ...) 是标准方式,兼容 Chrome 58+、Firefox 63+、Edge 79+
  • 事件回调中应重新读取 screen.orientation.typescreen.orientation.angle,不要依赖闭包缓存值
if ("orientation" in screen) {   const handler = () => {     console.log("当前方向:", screen.orientation.type);     console.log("旋转角度:", screen.orientation.angle);   };   screen.orientation.addEventListener("change", handler);   // 初始值也手动触发一次   handler(); }

尝试锁定屏幕方向时常见的 PermissionDenied 和 NotAllowedError

screen.orientation.lock() 是受权限和上下文严格限制的异步操作,失败非常常见,不能假设它一定成功。

立即学习前端免费学习笔记(深入)”;

  • 必须在用户手势(如 clicktouchend)触发的回调中首次调用,否则抛 NotAllowedError
  • 若用户之前拒绝过方向锁定权限,会触发 PermissionDenied(但目前 Chrome 不弹明确提示,只静默失败)
  • 某些全屏模式下(如 document.documentElement.requestFullscreen() 后)才允许锁方向;普通页面中调用常被忽略
  • 锁定后若用户强制旋转设备,部分浏览器(如 Firefox)会自动解除锁定,需监听 change 事件捕获该状态回退

真正稳定可控的方向感知,仍应以 window.innerWidth > window.innerHeight 为 fallback 主逻辑,screen.orientation 仅作增强补充。

text=ZqhQzanResources