uni-app小程序吸顶

1,css方式实现

// 纯css吸顶
			position: -webkit-sticky;
			position: sticky;
			top: var(--window-top);
			z-index: 99;

2,利用js

<view class="select-tab" :class="isFixedTop?'fixed':''" id="navbar">
			<view class="tab-item" v-for="(item,index) in tabList" :key="index" @tap="clickTab(index)" :class="isShow == index ? 'tab-item2' : 'tab-item'">
				<view class="first">
					<text class="one">{{item.txt}}</text>
					<text class="two" v-if="index == 0">{{songTotal}}</text>
					<text class="two" v-if="index == 1">{{ablumTotal}}</text>
					<text class="two" v-if="index == 2">{{mvTotal}}</text>
				</view>
				<view class="line" v-if="isShow == index"></view>
			</view>
		</view>
data(){
	return{
		tabInitTop: 0, //导航栏初始化距顶部的距离
		isFixedTop: false, //是否固定顶部
	}
}

在刚进页面的时候获取元素到顶部的距离

	onLoad(option) {
			if (this.tabInitTop== 0) {
				//获取节点距离顶部的距离
				uni.createSelectorQuery().select('#navbar').boundingClientRect((res) => {
					console.log(res);
					if (res && res.top > 0) {
						var tabInitTop= res.top;
						this.tabInitTop= tabInitTop
					}
				}).exec();
			}
		},

滚动事件

		onPageScroll(e) {
			var scrollTop = e.scrollTop
			console.log(scrollTop);
			console.log(this.tabInitTop);
			var isSatisfy = scrollTop >= this.tabInitTop? true : false;
			//只有处于吸顶的临界值才会不相等
			if (this.isFixedTop === isSatisfy) {
				return false;
			}
			console.log(this.isFixedTop);
			this.isFixedTop = isSatisfy
		},

你可能感兴趣的:(小程序)