美好的心情.jpeg
那么我们怎么在微信小程序也实现这么一个效果呢? 首先写一个非常简单列表:
<view class='header'>这里是header</view> <view class='section-header'>这是section-header</view> <block wx:for="{{testData}}"> <view class='section-cell'>{{item}}</view> </block>
.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
在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() },
fixed用来控制是否悬停
/** * 页面滚动监听 */ onPageScroll: function (e) { //console.log(e) this.setData({ scrollTop: e.scrollTop }) if (e.scrollTop > this.data.sectionHeaderLocationTop) { this.setData({ fixed: true }) } else { this.setData({ fixed: false }) } },
<view class='{{fixed ? "section-header section-fixed": "section-header"}}'>这是section-header</view> <view hidden='{{!fixed}}' class="section-header section-placeholder"></view>
.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
所以在我们改变高度之后,要再次调用该函数去获取距离"当前顶部"的距离,这也是要注意的一个点,如果我能直接再次获取并赋值,发现还是有问题,就是因为此时获取的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()
加上此时页面滚动的距离,则能保证我们预期的效果出现!!!!
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句