【问题标题】:How to get device width and height in Ionic using TypeScript?如何使用 TypeScript 在 Ionic 中获取设备宽度和高度?
【发布时间】:2016-12-08 19:20:47
【问题描述】:

我正在尝试使用 typescript 在 ionic 2 中获取设备宽度和高度。

在我之前使用的 ionic 2 版本中,

window.screen.width
window.screen.height

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

Type Script + ionic 2 是如何工作的?

【问题讨论】:

    标签: angular typescript ionic-framework ionic2 ionic3


    【解决方案1】:

    您可以为此使用平台信息。

    在内部 platform 使用 window.innerWidthwindow.innerHeight 但是

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

    离子 4/5

    文档https://ionicframework.com/docs/angular/platform#width-number

    import { Component } from '@angular/core';
    import { Platform } from '@ionic/angular';
    
    @Component({...})
    export MyApp {
      constructor(platform: Platform) {
        platform.ready().then(() => {
          console.log('Width: ' + platform.width());
          console.log('Height: ' + platform.height());
        });
      }
    }
    

    离子 2/3

    文档https://ionicframework.com/docs/v3/api/platform/Platform/#width

    import { Component } from '@angular/core';
    import { Platform } from 'ionic-angular';
    
    @Component({...})
    export MyApp {
      constructor(platform: Platform) {
        platform.ready().then(() => {
          console.log('Width: ' + platform.width());
          console.log('Height: ' + platform.height());
        });
      }
    }
    

    【讨论】:

    • 按照 ionic 2 的标准,这应该是公认的答案
    • 如果您使用 ionic 4+,请将导入语句从 import {Platform} from 'ionic-angular'; 更改为 import {Platform} from '@ionic/angular';
    • @DavidAddoteye 同意!
    【解决方案2】:

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

    【讨论】:

    • 这将触发 DOM 重绘,这很昂贵。请参阅其他答案。
    猜你喜欢
    • 2014-07-27
    • 1970-01-01
    • 2012-04-27
    • 2012-11-07
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    相关资源
    最近更新 更多