微信小程序自动获取顶部导航栏高度

1、本人是通过uniapp开发的微信小程序,原生开发基本相同,首先在data里声明变量

data{
    return{
        menuButtonInfo: '',
		navHeight: '',
		searchMarginTop: '',
		searchHeight: '',
		searchWidth: '',
    }
}

2、其次在onLoad生命周期中获取当前手机的导航栏宽高数据

onLoad: function(e) {
			this.menuButtonInfo = wx.getMenuButtonBoundingClientRect()
			const {
				top,
				width,
				height,
				right
			} = this.menuButtonInfo
			wx.getSystemInfo({
				success: (res) => {
					const {
						statusBarHeight
					} = res
					const margin = top - statusBarHeight
					this.navHeight = (height + statusBarHeight + (margin * 2)),//导航栏总高
					this.searchMarginTop = statusBarHeight + margin, // 状态栏 + 胶囊按钮边距
					this.searchHeight = height, // 与胶囊按钮同高
					this.searchWidth = right - width // 胶囊按钮右边坐标 - 胶囊按钮宽度 = 按钮左边可使用宽度
				},
			})
}

3、navHeight获取的是当前手机型号的导航栏总高度;searchMarginTop获取的是手机顶部到小程序胶囊的高度,也就是下图黄色线框的高度;searchHeight获取的是胶囊的高度,也就是下图绿色线框的高度;searchWidth获取的是屏幕左侧到胶囊左侧的宽度,也就是下图中黑色线框的宽度。

 注:全靠闫皇一手教我。

猜你喜欢

转载自blog.csdn.net/sxy323/article/details/128232976
今日推荐