// 获取自定义导航的高
uni.getSystemInfo({
success: res => {
this.topHeight = res.statusBarHeight
}
})
console.log(this.topHeight);
在小程序平台,如果原生导航栏被隐藏,仍然在右上角会有一个悬浮按钮,微信下也被称为胶囊按钮。本API用于获取小程序下该菜单按钮的布局位置信息,方便开发者布局顶部内容时避开该按钮。
//获取胶囊按钮
let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
下面来尝试一下:
代码如下:【注释中为获取自定义导航的api】
export default {
components: {
bottomIcon
},
data() {
return {
titleheight: 0,
titletop:0,
}
},
onLoad() {
// 获取自定义导航的高
// uni.getSystemInfo({
// success: res => {
// this.topHeight = res.statusBarHeight
// }
// }),
this.getHeight();
// console.log("topHeight的值", this.topHeight);
},
methods: {
getHeight() {
let res = uni.getMenuButtonBoundingClientRect();
this.titletop = res.top;
this.titleheight = res.height
console.log(res);
console.log("titletop的值", this.titletop);
console.log("titleheight的值", this.titleheight);
console.log("一半的titleheight的值", this.titleheight/2);
}
}
}
</script>
在onLoad中调用一下this.getHeight();这个方法,得到返回值胶囊按钮距离顶部的top值以及自身的宽高,就可以用来自定义自己的导航栏,实现不同机型的兼容性。
//定义一下这个盒子的距离顶部的top值等于胶囊按钮的top
// 所以会在各个机型都保持与胶囊按钮在同一水平线
// 这里使用 v-bind 并没有使用插值语法{{titletop}}
<view class="back" :style="'top:'+ titletop+'px'">
</view>
.back{
position: absolute;//不写定位应该top不生效,可以自行试一下
}
还是挺有趣的。
如果是需要计算【顶部距离+胶囊按钮的高+底部空出间距】
<view class="top_view" :style="'margin-top:'+ (titletop+titleheight+10)+'px'" >
</view>
放一张图就明白了:1、2、3分别对应 titletop 、 titleheigh 、 10
这样写出来兼容度较高。
自己复制粘贴用:
// view中 (添加此标签后 最上边的盒子正好与胶囊按钮平齐,可以加一个PX值让它向下移动距离)
:style="'margin-top:'+ (titletop+titleheight+10)+'px'"
// data return中
titleheight: 0,
titletop:0,
// OnLoad中
this.getHeight();
//methods中
getHeight() {
let res = uni.getMenuButtonBoundingClientRect();
this.titletop = res.top;
this.titleheight = res.height
}
也可以简单封装一下:放入全局app.vue中:文章来源:https://www.toymoban.com/news/detail-582536.html
<!-- 全局 -->
<script>
export default {
globalData() {
return {
titleheight: 0,
titletop: 0,
}
},
onLaunch: function() {
},
onLoad: function() {
},
onShow: function() {
console.log('App Show')
},
onHide: function() {
console.log('App Hide')
},
methods: {
getHeight() {
let res = uni.getMenuButtonBoundingClientRect();
this.titletop = res.top;
this.titleheight = res.height
},
},
}
</script>
<style>
/*每个页面公共css */
</style>
在需要的地方直接引入就行:【封装的并不好,暂且先用着。可以少写一个getHeight()方法】文章来源地址https://www.toymoban.com/news/detail-582536.html
<template>
<view> </view>
</template>
<script>
export default {
data(){
return{
titleheight:0,
titletop:0
}
},
onLoad() {
//通过全局vue得到getHeight()
getApp().getHeight();
this.titleheight = getApp().titleheight;
this.titletop = getApp().titletop;
},
methods: {
}
到了这里,关于【uniapp】小程序获取自定义导航高与胶囊按钮定位的两个api的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!