需求:滚动到一定位置,固定,不再滚动,实现吸顶效果。
思路一:
使用原生滚动,给需要吸顶的组件添加样式
.tab-control{ position: sticky; /* 从顶部向下滚动44px,固定,不在向下滚动。向上y小于44px恢复滚动*/ top: 44px }
思路二:
hack的方法(偷梁换柱,better-scroll局部滚动使用较多)
复制两份需要吸顶的组件A和B,将A组件布局放在需要吸顶的位置,默认不显示,监听滚动的位置,当B组件来到A位置的时候,A显示出来,B会更随文档流一起往上走了,B再回来的时候,A再掩藏。
如果吸顶A、B组件有动态样式,需将两个动态样式的标志位设置成一致。
<template> <div id="home"> <NavBar class='home-nav'> <div slot="center">安琪拉购物街</div> </NavBar> <!-- 吸顶A --> <TabControl class="tab-control" :titles="['流行','新款','精选']" @tabClick="tabClick" ref='tabControl1' v-show="isTabFixed"/> <!-- 局部滚动--> <Scroll class="content" ref='scroll' :probe-type='3' @scroll="contentScroll" :pullUpload="true" @pullingUp = "loadMore" > <HomeSwiper :banners = 'banners' @swiperImageLoad = 'swiperImageLoad'/> <RecommendView :recommends = "recommends" /> <FeatureView/> <!-- 吸顶B --> <TabControl :titles="['流行','新款','精选']" @tabClick="tabClick" ref='tabControl2' /> <GoodsList :goods = "showGoods" /> </Scroll> </div> </template> <script> import TabControl from 'components/content/tabControl/TabControl'; export default { name: "Home", components: { TabControl, }, data() { return { tabOffsetTop: 0, isTabFixed: false, currentType: 'pop' } }, methods: { /** * 事件监听相关 */ tabClick(index){ console.log("0") switch(index){ case 0: this.currentType = "pop"; break; case 1: this.currentType = 'new'; break; case 2: this.currentType = "sell"; break } this.$refs.tabControl1.currentIndex = index; this.$refs.tabControl2.currentIndex = index; }, contentScroll(position){ // 决定tabControl是否吸顶(position: fixed) this.isTabFixed = (-position.y) > this.tabOffsetTop }, }, } </script> <style scoped> #home{ padding-top: 44px; /* 100vh是视图窗口的高度 */ height: 100vh; position: relative; } .home-nav{ background-color: var(--color-tint); color: #fff; /* 在使用浏览器使用原生滚动时,为了让导航不跟随一起滚动 */ position: fixed; left: 0; right: 0; top: 0; z-index: 9; } /* 吸顶固定 */ .tab-control{ position: relative; z-index: 9; } </style>
home.vue项目完整版
<template> <div class="tab-control" > <div v-for="(item , index) in titles" class="tab-control-item" :class="{active: index === currentIndex}" @click='itemClick(index)'> <span>{{item}}</span> </div> </div> </template> <script> export default { name: "TabControl", props: { titles:{ type: Array, default(){ return [] }}}, data(){ return{ currentIndex: 0 } }, methods: { itemClick(index){ this.currentIndex = index; this.$emit('tabClick', index) } }, } </script> <style> .tab-control{ display: flex; text-align: center; font-size: 15px; height: 40px; line-height: 40px; background-color: #fff; } .tab-control-item{ flex:1; } .tab-control-item span{ padding: 5px; } .active{ color: var(--color-high-text) } .active span{ border-bottom: 3px solid var(--color-tint); } </style>