微信小程序 - 获取用户手机屏幕高度与宽度(两种方案)

13

微信小程序 - 获取用户手机屏幕高度与宽度(两种方案)

微信小程序 - 获取用户手机屏幕高度与宽度

前言--------

有时候我们需要获取用户手机屏幕高度或宽度来完成一些界面表现,例如调整布局、计算元素位置等。在微信小程序中,我们可以通过两种方式实现这一点。下面是详细的描述。

第一种方案(推荐)

"vw" = "view width"

"vh" = "view height"

使用 CSS3 引入的 vw / vh 基于宽度/高度相对于窗口大小。

```cssapp {

width:100vw;

height:100vh;

}

```

在小程序中,我们可以直接使用 `wx.getSystemInfoSync()` 方法获取设备信息,包括屏幕宽度和高度。

```javascriptconst systemInfo = wx.getSystemInfoSync();

console.log(systemInfo.windowWidth); // 获取窗口宽度console.log(systemInfo.windowHeight); // 获取窗口高度```

第二种方案

如果你需要在小程序中获取设备的物理屏幕宽度和高度(而不是窗口大小),可以使用 `wx.getSystemInfoSync()` 方法中的 `screenWidth` 和 `screenHeight` 属性。

```javascriptconst systemInfo = wx.getSystemInfoSync();

console.log(systemInfo.screenWidth); // 获取物理屏幕宽度console.log(systemInfo.screenHeight); // 获取物理屏幕高度```

注意:在 iOS 设备上,`screenWidth` 和 `screenHeight` 的值可能会比实际的物理屏幕大小大一些,因为它们包括了状态栏和导航栏的高度。

总结

微信小程序中获取用户手机屏幕高度与宽度有两种方案。第一种方案使用 CSS3 引入的 vw / vh 基于宽度/高度相对于窗口大小,推荐使用 `wx.getSystemInfoSync()` 方法获取设备信息。第二种方案直接使用 `wx.getSystemInfoSync()` 方法中的 `screenWidth` 和 `screenHeight` 属性获取物理屏幕宽度和高度。

参考代码

```javascript// 第一种方案Page({

data: {

screenWidth: '',

screenHeight: ''

},

onLoad() {

const systemInfo = wx.getSystemInfoSync();

this.setData({

screenWidth: systemInfo.windowWidth,

screenHeight: systemInfo.windowHeight });

}

});

```

```javascript// 第二种方案Page({

data: {

screenWidth: '',

screenHeight: ''

},

onLoad() {

const systemInfo = wx.getSystemInfoSync();

this.setData({

screenWidth: systemInfo.screenWidth,

screenHeight: systemInfo.screenHeight });

}

});

```

注意事项

* 在 iOS 设备上,`screenWidth` 和 `screenHeight` 的值可能会比实际的物理屏幕大小大一些,因为它们包括了状态栏和导航栏的高度。

* 使用 `wx.getSystemInfoSync()` 方法获取设备信息时,请确保在 `onLoad` 或 `onShow` 生命周期函数中调用该方法,以避免获取到的信息过旧。

小程序微信小程序csscss3

版权声明:除非特别标注,否则均为网络文章,侵权请联系站长删除。

上一篇 一键查询微信加过那些群聊

下一篇 【微信篇】取证遇到微信昵称、微信号、微信账号、微信ID一次性区分清楚