微信小程序获取屏幕大小的方式
微信小程序提供了多种方式获取屏幕大小,各有不同特点。以下是常见的几种方法及其实现代码:
使用 wx.getSystemInfoSync()
该方法同步获取系统信息,可直接返回屏幕宽度和高度,适用于多数场景。
const systemInfo = wx.getSystemInfoSync();
const screenWidth = systemInfo.screenWidth;
const screenHeight = systemInfo.screenHeight;
console.log('屏幕宽度:', screenWidth, '屏幕高度:', screenHeight);
特点:
- 同步调用,直接返回结果,无需回调。
- 包含屏幕的物理像素值(单位为px)。
- 同时可获取其他系统信息(如窗口高度、状态栏高度等)。
使用 wx.getSystemInfo()
异步获取系统信息,通过回调函数返回结果,适合需要异步处理的场景。
wx.getSystemInfo({
success(res) {
const screenWidth = res.screenWidth;
const screenHeight = res.screenHeight;
console.log('屏幕宽度:', screenWidth, '屏幕高度:', screenHeight);
}
});
特点:
- 异步调用,避免阻塞主线程。
- 返回结果与同步方法一致。
使用 wx.getWindowInfo()
该方法返回窗口信息,包括屏幕尺寸和安全区域(如刘海屏适配)。
const windowInfo = wx.getWindowInfo();
const screenWidth = windowInfo.screenWidth;
const screenHeight = windowInfo.screenHeight;
console.log('屏幕宽度:', screenWidth, '屏幕高度:', screenHeight);
特点:
- 支持安全区域(safeArea)信息,适合全面屏适配。
- 同步调用,返回结果更全面。
使用 wx.getDeviceInfo()
获取设备信息,包括屏幕尺寸和像素比(pixelRatio)。
const deviceInfo = wx.getDeviceInfo();
const screenWidth = deviceInfo.screenWidth;
const screenHeight = deviceInfo.screenHeight;
console.log('屏幕宽度:', screenWidth, '屏幕高度:', screenHeight);
特点:
- 包含设备像素比(
pixelRatio
),可用于高清屏适配。 - 同步调用,返回设备级信息。
注意事项
-
单位差异:上述方法返回的屏幕尺寸单位为物理像素(px),若需转换为rpx,需结合
screenWidth
计算:const rpxRatio = 750 / systemInfo.screenWidth; const rpxValue = pxValue * rpxRatio;
-
全面屏适配:对于刘海屏或安全区域,建议使用
wx.getWindowInfo()
的safeArea
属性。 -
异步与同步:根据场景选择同步或异步方法,避免同步调用阻塞渲染。
-
兼容性:部分方法(如
wx.getDeviceInfo()
)需基础库版本支持,建议检查兼容性。