我们知道当对一个元素设置了 position: fixed;
后,该元素会脱离文档流,下面的内容会顶上来,导致被内容被遮盖。常见的一个做法是设置下面内容的 padding
或 margin
,虽然能达到效果,但是总归不完美,特别是当我们想封装一个组件给别人用的时候,还得让别人设置一下样式,这样岂不麻烦,所以就有了下面这个方法,以我封装的这个 vue
header
组件为例
html
<div :class="classList">
<div class="i-nav-bar__inner">
<div class="i-nav-bar__left" @click="handleClickLeft">
<slot name="left">
<i class="i-nav-bar__arrow fa fa-fw fa-angle-left" v-if="leftArrow"></i>
<span class="i-nav-bar__text" v-if="leftText">{{ leftText }}</span>
</slot>
</div>
<div class="i-nav-bar__title">
<slot name="title">{{ title }}</slot>
</div>
<div class="i-nav-bar__right" @click="handleClickRight">
<slot name="right"></slot>
</div>
</div>
</div>
js
export default {
name: 'INavBar',
props: {
title: String,
leftArrow: Boolean,
leftText: String,
fixed: Boolean
},
computed: {
classList() {
return [
'i-nav-bar',
{
'i-nav-bar--fixed': this.fixed
}
]
}
},
methods: {
handleClickLeft(ev) {
this.$emit('click-left', ev)
},
handleClickRight(ev) {
this.$emit('click-right', ev)
}
}
}
scss
$height: 50px;
.i-nav-bar {
height: $height;
&__inner {
position: relative;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.07);
height: $height;
background-color: #fff;
color: #4a4d5a;
}
&__left {
height: 100%;
position: absolute;
top: 0;
left: 10px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
&:active {
opacity: 0.5;
}
.i-nav-bar__arrow {
font-size: 25px;
margin-top: -1px;
}
.i-nav-bar__text {
font-size: 14px;
margin-left: -6px;
}
}
&__title {
max-width: 50%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
margin: 0 auto;
font-size: 16px;
color: #34495e;
}
&__right {
height: 100%;
position: absolute;
top: 0;
right: 10px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
&:active {
opacity: 0.5;
}
}
&--fixed {
.i-nav-bar__inner {
position: fixed;
z-index: 1;
top: 0;
left: 0;
width: 100%;
}
}
}
外面套一个父元素,height
假设为 50px,然后我们对里面这个元素设置 position: fixed;
,它的 height
也设置 50px,这样的话虽然里面脱离了文档流,但是父元素依然占据着空间,所以下面的元素也就不会顶上来,当别人使用你的组件时再也不用费力设置 padding
或 margin
了。
图中头部是上面示例代码的效果图,tabbar 是我封装的另一个组件,这里为了演示效果,我把他们放到一起
