98 lines
2.7 KiB
JavaScript
98 lines
2.7 KiB
JavaScript
|
|
/**
|
|||
|
|
* 系统信息工具类
|
|||
|
|
* 用于获取状态栏和微信胶囊按钮信息
|
|||
|
|
*/
|
|||
|
|
class SystemInfoUtil {
|
|||
|
|
constructor() {
|
|||
|
|
// 缓存系统信息,避免重复获取
|
|||
|
|
this.systemInfo = null;
|
|||
|
|
// 缓存微信胶囊按钮信息
|
|||
|
|
this.menuButtonInfo = null;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 初始化系统信息
|
|||
|
|
* @returns {Promise} 包含系统信息的Promise对象
|
|||
|
|
*/
|
|||
|
|
init() {
|
|||
|
|
return new Promise((resolve, reject) => {
|
|||
|
|
// 如果已经获取过信息,直接返回缓存
|
|||
|
|
if (this.systemInfo && this.menuButtonInfo) {
|
|||
|
|
resolve({
|
|||
|
|
systemInfo: this.systemInfo,
|
|||
|
|
menuButtonInfo: this.menuButtonInfo
|
|||
|
|
});
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 获取系统信息
|
|||
|
|
uni.getSystemInfo({
|
|||
|
|
success: (res) => {
|
|||
|
|
this.systemInfo = res;
|
|||
|
|
|
|||
|
|
// 获取微信胶囊按钮信息
|
|||
|
|
this.menuButtonInfo = uni.getMenuButtonBoundingClientRect();
|
|||
|
|
|
|||
|
|
resolve({
|
|||
|
|
systemInfo: this.systemInfo,
|
|||
|
|
menuButtonInfo: this.menuButtonInfo
|
|||
|
|
});
|
|||
|
|
},
|
|||
|
|
fail: (err) => {
|
|||
|
|
console.error('获取系统信息失败', err);
|
|||
|
|
reject(err);
|
|||
|
|
}
|
|||
|
|
});
|
|||
|
|
});
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 获取状态栏高度
|
|||
|
|
* @returns {number} 状态栏高度,单位px
|
|||
|
|
*/
|
|||
|
|
getStatusBarHeight() {
|
|||
|
|
return this.systemInfo?.statusBarHeight || 0;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 获取微信胶囊按钮信息
|
|||
|
|
* @returns {Object} 胶囊按钮信息对象
|
|||
|
|
*/
|
|||
|
|
getMenuButtonInfo() {
|
|||
|
|
return this.menuButtonInfo || {};
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 计算自定义导航栏高度
|
|||
|
|
* @returns {number} 自定义导航栏高度,单位px
|
|||
|
|
*/
|
|||
|
|
getCustomNavBarHeight() {
|
|||
|
|
if (!this.systemInfo || !this.menuButtonInfo) {
|
|||
|
|
console.warn('请先调用init()方法初始化系统信息');
|
|||
|
|
return 0;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 胶囊按钮高度 + (胶囊顶部距离 - 状态栏高度) * 2
|
|||
|
|
return this.menuButtonInfo.height + (this.menuButtonInfo.top - this.systemInfo.statusBarHeight) * 2;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 获取屏幕宽度
|
|||
|
|
* @returns {number} 屏幕宽度,单位px
|
|||
|
|
*/
|
|||
|
|
getScreenWidth() {
|
|||
|
|
return this.systemInfo?.windowWidth || 0;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 获取屏幕高度
|
|||
|
|
* @returns {number} 屏幕高度,单位px
|
|||
|
|
*/
|
|||
|
|
getScreenHeight() {
|
|||
|
|
return this.systemInfo?.windowHeight || 0;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 导出单例实例,确保全局使用同一个对象
|
|||
|
|
export default new SystemInfoUtil();
|