uniapp实现微信小程序吸顶效果

当我们页面滑动到一定位置的时候,让这个组件固定,之后再滑动到一定位置时候,回归原页面,还有点击立即到最顶部效果

如果是移动端的话,可以用一个position: sticky;不过要考虑兼容性

uniapp怎么做呢?

比如想让这个组件,滑动到一定位置吸顶

<Delicacy id="boxFixed" :class="{'is_fixed' : isfixed}"></Delicacy>

  data(){
      return{
         rect:''    //页面滚动距离
         menutop:''  //组件距离顶部的距离
     }
  }

首先监听页面滚动距离

    onPageScroll(e) {
		// console.log(e.scrollTop)
		this.rect = e.scrollTop
	},

然后监听组件距离顶部的距离

 onLoad() {
		// 监听筛选组件距离顶部的距离
		const query = uni.createSelectorQuery()
		query.select('#boxFixed').boundingClientRect()
		query.exec((res) => {
			this.menutop = res[0].top
		})
	},

然后通过computed计算

computed: {
	// 监听筛选组件置顶和不置顶
	namepage() {
	// 如果页面滚动的高度大于筛选组件距离顶部的高度,那就置顶,反之不置顶
				if (this.rect > this.menutop) {
					this.isfixed = true
				} else {
					this.isfixed = false
				}
			},
		},

css

   .is_fixed {
		position: fixed;
		left: 0;
		top: 0;
		right: 0;		
}

这样就完成了吸顶效果,如果我们想点击这个组件,它立即回到顶部呢?

   <view @click="poll()" :catchtouchmove="true">
		<Delicacy id="boxFixed" :class="{'is_fixed' : isfixed}"></Delicacy>
	</view>

   data(){
      return{
       topdata:''
     }
  }
   methods:{
     // 回到顶部
			poll() {
				uni.pageScrollTo({
					scrollTop: this.topdata + 2,
					duration: 300
				})
			},
   },
   onLoad() {
		// 监听筛选组件距离顶部的距离
		const query = uni.createSelectorQuery()
		query.select('#boxFixed').boundingClientRect()
		query.exec((res) => {
			this.topdata = res[0].top
		})
	},

这样即可

  • 4
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值