简体   繁体   English

使用 JavaScript 检测屏幕方向

[英]Detect screen orientation with JavaScript

I need to detect the change between the orientation of a device at runtime: trying to use the Screen Api ( https://developer.mozilla.org/en-US/docs/Web/API/Screen/orientation ) on an Angular project I am receiving an error: Property 'orientation' does not exist on type 'Screen' .我需要在运行时检测设备方向之间的变化:尝试在 Angular 项目中使用 Screen Api ( https://developer.mozilla.org/en-US/docs/Web/API/Screen/orientation )我收到一个错误: Property 'orientation' does not exist on type 'Screen'
Orientation is not present in the Screen interface!屏幕界面中不存在方向!

That some solutions that I was trying to replicate, without having success:我试图复制的一些解决方案,但没有成功:
- How do I correctly detect orientation change using javascript and Phonegap in IOS? - 如何在 IOS 中使用 javascript 和 Phonegap 正确检测方向变化?

How could I achieve it in a cross-browser friendly way?我怎样才能以跨浏览器友好的方式实现它?

Scenario:设想:

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

I suppose a possible, simple solution would be something like this:我想一个可能的、简单的解决方案是这样的:

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

The orientation read-only property of the Screen interface returns the current orientation of the screen. Screen接口的orientation只读属性返回屏幕的当前方向。

Syntax语法

var orientation = window.screen.orientation;

Example示例

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM