在移动端中,吸顶效果是非常常见的,在这里将它封装成了一个组件,如果在项目中有很多地方要用到,建议把它放到src/common里面,使用也非常的简单(源码在最下面)
1.使用方法
为了方便演示,这里使用了for循环的方法将屏幕撑满,直接将全部代码复制到你的编辑器上运行就能看到效果
<template>
<div>
<ul>
<li v-for="(item,index) in headerData" :key="index">{{item}}</li>
</ul>
<sticky-slot class="stickyTop"> <!--加一个class-->
<div class="tab">
假装这是一个tab栏,当页面滚动的时候要固定在顶部
</div>
</sticky-slot>
<ul>
<li v-for="(item,index) in footerData" :key="index">{{item}}</li>
</ul>
</div>
</template>
<script>
import stickySlot from './stickySlot' //改成你自己存放的路径
export default {
data(){
return{
headerData : [],
footerData : []
}
},
created(){
for(let i=0;i<20;i++){
this.headerData.push('第'+ i + '条数据')
};
for(let i=20;i<80;i++){
this.footerData.push('第'+ i + '条数据')
}
},
components:{
stickySlot
}
}
</script>
<style>
.stickyTop{
top:0; /*top的值是距离顶部多少固定*/
z-index:10;
}
.tab{
height:30px;
line-height: 30px;
background-color:greenyellow;
}
</style>
效果图
到达顶部的时候固定在顶部,内容部分继续滚动
sticky源码(兼容)
<template>
<div class="sticky" :style="getPosition">
<div class="sticky-warp">
<slot></slot>
</div>
</div>
</template>
<script type="text/babel">
export default {
data () {
return {}
},
computed: {
getPosition(){
var position = this.cssSupport('position', 'sticky') ? 'sticky' : 'relative';
return 'position:' + position;
}
},
props: {},
beforeMount () {
},
mounted(){
this.init();
},
deactivated(){
if(this.cssSupport('position', 'sticky')) {
return;
}
/*复位*/
var elWarp = this.$el.querySelector('.sticky-warp');
elWarp.position = 'absolute';
},
methods: {
init(){
if (this.cssSupport('position', 'sticky')) {
return;
}
var el = this.$el, target = this.$el.parentNode,
elWarp = this.$el.querySelector('.sticky-warp'),
top = this.getNumberValue(document.defaultView.getComputedStyle(el).top);
this.addScrollListen(target, (event)=> {
if (el.getBoundingClientRect().top <= top) {
elWarp.style.position = 'fixed';
}
if (el.getBoundingClientRect().top >= 0 && elWarp.style.position != 'absolute') {
elWarp.style.position = 'absolute';
}
})
},
cssSupport: function (attr, value) {
var element = document.createElement('div');
if (attr in element.style) {
element.style[attr] = value;
return element.style[attr] === value;
} else {
return false;
}
},
getNumberValue(pxValue){
var value = String(pxValue).match(/^\-?\+?[0-9]+/g);
return value ? Number(value) : undefined;
},
addScrollListen(target, cb){
target.addEventListener('y-scroll', (event)=> {
cb && cb(event);
});
}
},
}
</script>
<style>
.sticky {
width: 100%;
}
.sticky .sticky-warp {
width: 100%;
background: inherit;
will-change: change;
height: inherit;
top: inherit;
}
</style>