如何使用Type Script获取Ionic 2中的设备宽度和高度?

Jig*_*hta 34 typescript ionic-framework ionic2 ionic3 angular

我试图使用打字稿获取离子2中的设备宽度和高度.

在以前版本的离子2我用过,

window.screen.width
window.screen.height
Run Code Online (Sandbox Code Playgroud)

但在较新版本中,这不起作用.

如何使用Type Script + ionic 2?

seb*_*ras 81

您可以使用这样的平台信息:

import {Component} from '@angular/core';
import {Platform} from 'ionic-angular';

@Component({...})
export MyApp {
  constructor(platform: Platform) {
    platform.ready().then((readySource) => {
      console.log('Width: ' + platform.width());
      console.log('Height: ' + platform.height());
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

就像你在Ionic docs中看到的那样,在内部platform使用the window.innerWidthwindow.innerHeightbut

使用此方法是首选,因为维度是缓存值,这减少了多次和昂贵的DOM读取的机会.

  • 这应该是接受的答案,因为它符合离子2的标准 (3认同)
  • 如果您使用 ionic 4+,请将导入语句从 `import {Platform} from 'ionic-angular';` 更改为 `import {Platform} from '@ionic/angular';` (2认同)

Ais*_*App 6

尝试使用window.innerHeight和window.innerWidth分别获取设备的高度和宽度.

  • 这将触发 DOM 重绘,这是昂贵的。请参阅另一个答案。 (2认同)