【问题标题】:Detect screen orientation with JavaScript使用 JavaScript 检测屏幕方向
【发布时间】:2018-04-16 10:55:32
【问题描述】:

我需要在运行时检测设备方向之间的变化: 尝试在 Angular 项目中使用 Screen Api (https://developer.mozilla.org/en-US/docs/Web/API/Screen/orientation) 我收到一个错误:Property 'orientation' does not exist on type 'Screen'
屏幕界面中不存在方向!

我试图复制的一些解决方案没有成功:
- How do I correctly detect orientation change using javascript and Phonegap in IOS?

如何以跨浏览器友好的方式实现它?

场景:

count = 0;
countState() {
  (window.screen.orientation.type === 'landscape-primary' || window.screen.orientation.type === 'landscape-secondary') ? count++ : count--;
}
<button (click)="countState()">Count</button>

【问题讨论】:

    标签: javascript angular window orientation screen-orientation


    【解决方案1】:

    Screen接口的orientation只读属性返回屏幕的当前方向。

    语法

    var orientation = window.screen.orientation;
    

    示例

    var 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 :(");
    }
    

    【讨论】:

      【解决方案2】:

      我想一个可能的、简单的解决方案是这样的:

      function getOrientation() {
        if (window.outerWidth > window.outerHeight) {
          return 'landscape';
        return 'portrait';
      }
      

      【讨论】:

      • 我刚刚在问题上添加了一个场景,以帮助您更好地了解我需要什么。 Pierre 在这里回复 (stackoverflow.com/a/4917796/6916104): On many devices, when the keyboard is shown, the availableWidth will be greater than the height, incorrectly giving landscape orientation. 不太确定这个解决方案是否适合我的需求。
      猜你喜欢
      • 1970-01-01
      • 2019-08-12
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-15
      相关资源
      最近更新 更多