uniAPP微信小程序 滚动到顶部固定悬浮

首先,先定义滚动的子组件ScrollContent , 定义data的属性:

data(){
	return {
			isFixed: false,
			nameTop: '',
			rect: 0,
	}
}

再在父组件中定义:

<ScrollContent id="scrollId" :class="{'is-fixed': isFixed}"></ScrollContent>

给他一个id是为了接下来的获取这一个组件,我们使用微信小程序的接口wx.createSelectorQuery,写在onLoad里面:

onLoad(){
			let that = this;
			const query = wx.createSelectorQuery();
			query.select('#scrollId').boundingClientRect();
			query.exec(function(res){
				console.log(res)
				if(res && res[0])
					that.nameTop = res[0].top
			})
		},

同时,监听页面的scroll事件,

onPageScroll(e){
				
				this.rect = e.scrollTop;
			}

然后我们使用计算属性,计算的原理是这样的:子组件一开始获得的距离顶部的值nameTop,还有滚动的时候距离顶部的值rect,如果rect-nameTop > 0, 说明已经该组件到了该固定的顶部的时候了,否则就把他的固定class取消:

computed: {
			//滑动组件置顶
			pageFixed(){
				if (this.rect > this.nameTop ){
					this.isFixed = true;
				}else{
					this.isFixed = false;
				}
			}
		}

为了使他能悬浮在顶部,我们首先想到的就是使用css的position:fixed属性:

.is-fixed{
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
	}

通过动态的设置isFixed的值,就可以动态的使他固定/不固定在顶部了

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