美文网首页
微信小程序____API调用之获取系统信息

微信小程序____API调用之获取系统信息

作者: OzanShareing | 来源:发表于2019-01-15 20:43 被阅读0次

    引言


    本文讲解微信小程序API调用之获取系统信息。

    作者主要的使用场景是获取设备的长度和宽度及屏幕可用的长度和宽度,不少小伙伴会有疑问,前面的文章中提起过小程序的设计方案,选择IPhone 6作为设计模板,使用rpx作为组件尺寸以达到自适应,为什么还需要获取设备的px长度,接下来慢慢解释。

    答疑解惑


    使用scroll-view时,需要设置高度,宽度很好去设置,使用rpx为单位的宽度变得很容易。然高度需要使用屏幕的实际尺寸作参考。

    接下来,我们来获取屏幕的长宽尺寸。

    正文


    获取系统信息有以下两种方式:

    • wx.getSystemInfo(Object object)

    • Object wx.getSystemInfoSync()

    wx.getSystemInfo(Object object)


    参数

    Object object

    属性 类型 默认值 必填 说明
    success function 接口调用成功的回调函数
    fail function 接口调用失败的回调函数
    complete function 接口调用结束的回调函数(调用成功、失败都会执行)

    object.success 回调函数

    参数

    Object res

    属性 类型 说明 最低版本
    brand string 设备品牌 1.5.0
    model string 设备型号
    pixelRatio number 设备像素比
    screenWidth number 屏幕宽度,单位px 1.1.0
    screenHeight number 屏幕高度,单位px 1.1.0
    windowWidth number 可使用窗口宽度,单位px
    windowHeight number 可使用窗口高度,单位px
    statusBarHeight number 状态栏的高度,单位px 1.9.0
    language string 微信设置的语言
    version string 微信版本号
    system string 操作系统及版本
    platform string 客户端平台
    fontSizeSetting number 用户字体大小(单位px)。以微信客户端「我-设置-通用-字体大小」中的设置为准 1.5.0
    SDKVersion string 客户端基础库版本 1.1.0
    benchmarkLevel number 设备性能等级(仅Android小游戏)。取值为:-2 或 0(该设备无法运行小游戏),-1(性能未知),>=1(设备性能值,该值越高,设备性能越好,目前最高不到50) 1.8.0

    示例代码

    wx.getSystemInfo({
      success(res) {
        console.log(res.model)
        console.log(res.pixelRatio)
        console.log(res.windowWidth)
        console.log(res.windowHeight)
        console.log(res.language)
        console.log(res.version)
        console.log(res.platform)
      }
    })
    

    Object wx.getSystemInfoSync()

    wx.getSystemInfo的同步版本

    返回值Object res

    示例代码

    try {
      const res = wx.getSystemInfoSync()
      console.log(res.model)
      console.log(res.pixelRatio)
      console.log(res.windowWidth)
      console.log(res.windowHeight)
      console.log(res.language)
      console.log(res.version)
      console.log(res.platform)
    } catch (e) {
      // Do something when catch error
    }
    

    详解

    1. windowHeight 概念

    可使用窗口高度,即:屏幕高度(screenHeight) - 导航(tabbar)高度

    2. 存在问题

    安卓设备下获取windowHeight不能准确得到对应的高度,总是拿到屏幕高度。

    3. 原因

    • 同步接口 wx.getSystemInfoSync 并不同步(猜测)

    wx.getSystemInfoSync只是在页面初始化时提前计算。所以对于 windowHeight 这种需要进行功能判断的属性,应该使用异步接口,实时获取。

    • wx.getSystemInfo 调用的时机不当

    上面讲了windowHeight 的定义,所以这个值取决于tabbar是否存在。
    为了保证 tabbar显示后再进行取值,建议在生命周期的onReady钩子中调用接口wx.getSystemInfo

    4. 最终方案

    在需要获取可使用窗口高度的对应js文件中,onReady 中调用wx.getSystemInfo

    相关文章

      网友评论

          本文标题:微信小程序____API调用之获取系统信息

          本文链接:https://www.haomeiwen.com/subject/izxudqtx.html