前言
提示:此篇是基于QQ小程序,但微信小程序的实现原理也基本都差不多。
所涉及到的知识点,先罗列一下:
1.监听页面滚动以及触发回顶部:onPageScroll
2.获取页面高度:createSelectorQuery // .select(’#page’).boundingClientRect
3.父子组件之间的传值:this.$组件名.setData({})
一、组件页面:放置滚回顶部按钮
<!-- button.qml --><view><image class="go-top-icon" hidden='{{!show}}' src="../../images/button_top.png" mode="widthFix"bindtap="goTop" /></view>
//button.jsdata: {show: false},// 回到顶部事件goTop() {if (qq.pageScrollTo) {qq.pageScrollTo({scrollTop: 0,duration: 300})}}
//button.qss .go-top-icon {width: 150rpx;height: 72rpx;margin: 0 auto;display: flex;align-items: center;justify-items: center;position: fixed;bottom: 200rpx;right: 40rpx;z-index: 9999;}
二、使用按钮组件的主页:监听滚动事件并处理
1.在主页应用组件
//index.json{"usingComponents": {"buttonChild": "/components/buttonChild/buttonChild"}}
<!-- index.qml --><!-- 设置id,以便后面获取页面高度 --><view id="page"><buttonChild id="button-child"></buttonChild>
2.监听页面滑动后处理事件
//index.js// 监听页面滑动onPageScroll(e) {const buttonChild = this.selectComponent('#button-child')this.$buttonChild = buttonChild// 获取页面高度const query = qq.createSelectorQuery()query.select('#page').boundingClientRect((rect) => {var bottom = Math.abs(rect.bottom - WIN_H)//WIN_N为屏幕显示区域高this.$buttonChild.setData({show: bottom < 5 })//从父组件判断并修改子组件的show值}).exec()}
如果此篇博客能帮得到你,欢迎大家关注,点赞,评论,收藏,转发呀~
如有不足也请在评论区提出批评指正!多多指教!
通过组件实现小程序底部Top按钮滑动到底部显示 其他情况则隐藏 点击按钮之后返回顶部的效果