使用JavaScript检测屏幕方向

时间:2017-11-03 16:26:15

标签: javascript angular window orientation screen-orientation

我需要在运行时检测设备方向之间的变化: 尝试在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>

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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