解决uniapp用了uni.getSystemInfo获取状态栏高度在app上获取不到问题
Posted on 2022-09-14 16:47 且行且思 阅读(1836) 评论(0) 编辑 收藏 举报出现的情况
刚开始写法 是用了
uni.getSystemInfo({
success:(e)=> {
this.statusBarHeight = e.statusBarHeight;
}
})
<template> <view class="main" :style="{marginTop:statusBarHeight+'px'}"> {{statusBarHeight}} <view>测试</view> </view> </template> <script> export default { name:"app-navbar", onLoad(){ uni.getSystemInfo({ success:(e)=> { this.statusBarHeight = e.statusBarHeight; } }) console.log(this.statusBarHeight,'-') }, data() { return { statusBarHeight:0, }; }, } </script> <style scoped lang="scss"> .main{ } </style>
解决问题的效果
第一种把那些方法不写在onLoad里面写在mounted里面就可以了
<template> <view class="main" :style="{marginTop:statusBarHeight+'px'}"> {{statusBarHeight}} <view>测试</view> </view> </template> <script> export default { name:"app-navbar", mounted(){ uni.getSystemInfo({ success:(e)=> { this.statusBarHeight = e.statusBarHeight; } }) console.log(this.statusBarHeight,'-') }, data() { return { statusBarHeight:0, }; }, } </script> <style scoped lang="scss"> .main{ } </style>
第二种是用了css识别法 var(--status-bar-height)
<template> <view class="main" style="margin-top: var(--status-bar-height);"> <view>测试</view> </view> </template> <script> export default { name:"app-navbar", onLoad(){ }, data() { return { }; }, methods:{ } } </script> <style scoped lang="scss"> .main{ } </style>
如果需要用到状态栏高度
可以这样获取到
<template> <view id="main" style="margin-top: var(--status-bar-height);"> <view>测试</view> 状态栏高度{{statusBarHeight}} </view> </template> <script> export default { name: "app-navbar", mounted() { const query = uni.createSelectorQuery().in(this); query.select('#main').boundingClientRect(data => { console.log("得到布局位置信息" + JSON.stringify(data)); console.log("节点离页面顶部的距离为" + data.top); this.statusBarHeight = data.top }).exec(); }, data() { return { statusBarHeight: 0, }; }, methods: { } } </script> <style scoped lang="scss"> .main {} </style>