设置fixed出现的问题
自定义小程序状态栏的时候想把自定义状态栏设置成fixed定位,但是发现设置了fixed之后下面会顶上来,
给下面的同级元素设置margin-top的话又带着上面的一起走。给content设置position:relative定位的top的话最下面(footer)的也会跑上来。(下面代码没有设置)
html
<view class="header">
header
</view>
<view class="content">
content
</view>
<view class="footer">
footer
</view>
css
.header {
width: 100%;
height: 200rpx;
background-color: green;
position: fixed;
opacity: 0.5;
}
.content {
margin-top: 100rpx;
width: 100%;
height: 100rpx;
background-color: royalblue;
}
.footer {
width: 100%;
height: 100rpx;
background-color: saddlebrown;
}
解决方法
一般自定义状态栏都是需要包装起来的,所以就在自定义状态栏进行处理了,看下面代码就可以啦。
也可以把自定义状态栏和内容区分成两块,然后给内容区设置定位的。但是这样使用的话,每个内容区都需要设置。(不推荐)
.top-fixed{
position: fixed;
width: 100%;
height: 100rpx;
background-color: darkcyan;
}
.top-space {
width: 100%;
height: 100rpx;
}
<view class="top">
<view class="top-fixed"></view>
<view class="top-space"></view>
</view>
<view class="footer"></view>
position: fixed会产生高度塌陷问题,设置一个空白容器是为了让父级有高度。这样子footer这个元素不会顶上去了。也不会影响到后序的元素了。
包装
<view>
<view class="top-bar" style="padding-top: {{ statauHeight }}px">
<view class="text" style="height: {{ navHeight }}px; line-height:{{ navHeight }}px">
<slot></slot>
</view>
</view>
<!-- 空 -->
<view class="space" style="height:{{ statauHeight + navHeight}}px"></view>
</view>
.top-bar {
position: fixed;
background-color: coral;
width: 100%;
}
.top-bar .text {
font-size: 28rpx;
margin-left: 22rpx;
}
// 这是组件的js文件,不是页面的。
data: {
statauHeight : 0,
navHeight : 0,
},
// 生命周期函数
attached: function() {
// 在组件实例进入页面节点树时执行
const menuBtn = wx.getMenuButtonBoundingClientRect();
const statusHeight = wx.getSystemInfoSync().statusBarHeight;
// top胶囊到最顶部的距离。menuBtn.top - statusHeight是状态栏与胶囊中间的距离
const navHeight = 2 * (menuBtn.top - statusHeight) + menuBtn.height
this.setData({
statauHeight : statusHeight,
navHeight : navHeight
})
效果图