
美好的心情.jpeg
很多APP都有这么一个效果,列表头在滚动到顶部时会悬停在顶部,比如在iOS开发中UITableview设置 style 属性设置为 Plain ,这个tableview的section header在滚动时会默认悬停在界面顶端。
那么我们怎么在微信小程序也实现这么一个效果呢?
首先写一个非常简单列表:
wxml代码
<view class='header'>这里是header</view><view class='section-header'>这是section-header</view> <block wx:for="{{testData}}"> <view class='section-cell'>{{item}}</view></block>
wxss代码
.header { height: 300rpx; width: 750rpx; background-color: bisque; margin-bottom: 10rpx;}.section-header { height: 80rpx; width: 750rpx; background-color: rebeccapurple;}.section-cell { height: 180rpx; width: 750rpx; background-color: gold; margin-top: 10rpx;}

简单列表效果.png
那我们要怎么样让头部悬停呢?
1、我们需要在页面布局完成后获取到头部的位置:
在onReady方法中,查询section-header节点并拿到该节点此时距离当前顶部的距离
注意是 此时,这个后面再讲
/** * 页面加载完成 */ onReady: function () { let that = this let query = wx.createSelectorQuery() query.select(".section-header").boundingClientRect(function (res) { // console.log(res) that.setData({ //section header 距离 ‘当前顶部’ 距离 sectionHeaderLocationTop: res.top }) }).exec() },
2、我们需要监听页面滚动:
fixed用来控制是否悬停
/** * 页面滚动监听 */ onPageScroll: function (e) { //console.log(e) this.data.scrollTop = e.scrollTop; if (e.scrollTop > this.data.sectionHeaderLocationTop) { this.setData({ fixed: true }) } else { this.setData({ fixed: false }) } },
3、修改相应的样式:
将原来的header修改为如下代码,并添加一个placeholder视图,目的是当我们的section-header视图悬停时,保持占位,避免页面抖动
<view class='{{fixed ? "section-header section-fixed": "section-header"}}'>这是section-header</view><view hidden='{{!fixed}}' class="section-header section-placeholder"></view>
增加wxss代码
.section-placeholder { background-color: white;}.section-fixed { position: fixed; top: 0;}
附上js data 代码:
data: { testData:[1,2,3,4,5,6,7,8,9,10], //section header 距离 ‘当前顶部’ 距离 sectionHeaderLocationTop: 0, //页面滚动距离 scrollTop: 0, //是否悬停 fixed: false },
此时我们需要的效果就实现了:

sectionHeader悬浮.gif
这个有一个要注意的点,我们在使用swlectorQuery()的时候,获取到的top是当前调用改函数时相应节点对应当前顶部的距离,这就有一个问题,当我们的header的高度(不一定是header只要是section-header上面的视图的高度)发生变化的时候,悬停就会有问题,因为我们的高度是最开始的时候获取的。
所以在我们改变高度之后,要再次调用该函数去获取距离"当前顶部"的距离,这也是要注意的一个点,如果我能直接再次获取并赋值,发现还是有问题,就是因为此时获取的top不是距离整个page页面顶部,而我们监听的页面滚动却是,所以我们可以修改代码如下:
let that = this let query = wx.createSelectorQuery() query.select(".section-header").boundingClientRect(function (res) { // console.log(res) that.setData({ //section header 距离 ‘当前顶部’ 距离 sectionHeaderLocationTop: res.top + that.data.scrollTop }) }).exec()
加上此时页面滚动的距离,则能保证我们预期的效果出现!!!!
赏我一个赞吧~~~
文章转载于:https://www.jianshu.com/p/1b949c64f5a8
原著是一个有趣的人,若有侵权,请通知删除
还没有人抢沙发呢~