首页 > 解决方案 > 如何在 iOS Safari 中获取当前屏幕方向?

问题描述

我正在尝试获取 iOS 的当前屏幕方向,但是我的功能适用于 chrome 开发工具模拟器和桌面,但不适用于 iOS。

这是我的功能:

export type ScreenOrientation = "landscape" | "portrait";

export function getScreenOrientation(): ScreenOrientation
{
  if (window.screen.availHeight > window.screen.availWidth)
    return "portrait";
  else
    return "landscape";
}

以下是我的程序如何粗略地检测屏幕方向变化并使用该功能:

  import { getScreenOrientation } from "../../Utils/getOrientation";
  const shoWPortraitModeError = getScreenOrientation() == "landscape" ? false : true;
  window.onorientationchange = function () {
    const newState = getScreenOrientation() == "landscape" ? false : true;
    console.log("window.onorientationchange: ", newState)
    shoWPortraitModeError  = newState;
  };

我尝试使用window.screen.heightwindow.screen.width但没有奏效。这是功能:

export type ScreenOrientation = "landscape" | "portrait";

export function getScreenOrientation(): ScreenOrientation
{
  if (window.screen.availHeight > window.screen.availWidth)
    return "portrait";
  else
    return "landscape";
}

我在 mac vm 上启动 iOS safari 调试器,我注意到window.screen当我转动屏幕时该值没有改变: 我注意到的事情

这让我想知道我可以使用哪些不同的属性来检测 ios 上的屏幕方向?

标签: javascriptiostypescriptmobile-safari

解决方案


在 safari 调试器的开发控制台的智能感知中挖掘之后,我发现可以使用window.innerHeightwindow.innerWidth属性来检测屏幕方向。

以下是如何使用该功能:

export type ScreenOrientation = "landscape" | "portrait";

export function getScreenOrientation(): ScreenOrientation
{
  if (window.innerHeight > window.innerWidth)
    return "portrait";
  else
    return "landscape";
}

推荐阅读