【问题标题】:How to get current screen orientation in iOS Safari?如何在 iOS Safari 中获取当前屏幕方向?
【发布时间】:2021-06-24 10:36:01
【问题描述】:

我正在尝试获取 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 上的屏幕方向?

【问题讨论】:

    标签: javascript ios typescript mobile-safari


    【解决方案1】:

    如果你想做一些 CSS,你可以使用媒体查询。

    https://developer.mozilla.org/en-US/docs/Web/CSS/@media/orientation

    基本上你可以使用@media (orientation: landscape) {}

    如果你想要在 JS 中,用于其他目的,你可以使用:

    let orientation = (screen.orientation || {}).type || screen.mozOrientation || screen.msOrientation;
    
    if (orientation === "landscape-primary") {
      console.log("That looks good.");
    } else if (orientation === "landscape-secondary") {
      console.log("Mmmh... the screen is upside down!");
    } else if (orientation === "portrait-secondary" || orientation === "portrait-primary") {
      console.log("Mmmh... you should rotate your device to landscape");
    } else if (orientation === undefined) {
      console.log("The orientation API isn't supported in this browser :(");
    }
    

    【讨论】:

    • 我最终使用了您的解决方案的 css 版本,因为 js 版本在 safari 中不起作用
    【解决方案2】:

    在 safari 调试器的 dev console 的智能感知中挖了一圈,发现可以使用window.innerHeightwindow.innerWidth 属性来检测屏幕方向。

    以下是如何使用该功能:

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

    【讨论】:

      猜你喜欢
      • 2011-04-09
      • 1970-01-01
      • 2021-06-04
      • 2013-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-28
      • 2017-04-04
      相关资源
      最近更新 更多