美好的心情.jpeg
很多APP都有這么一個效果,列表頭在滾動到頂部時會懸停在頂部,比如在iOS開發(fā)中UITableview設置 style 屬性設置為 Plain ,這個tableview的section header在滾動時會默認懸停在界面頂端。
那么我們怎么在微信小程序也實現(xiàn)這么一個效果呢页衙?
首先寫一個非常簡單列表:
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節(jié)點并拿到該節(jié)點此時距離當前頂部的距離
注意是 此時艰躺,這個后面再講
/**
* 頁面加載完成
*/
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、我們需要監(jiān)聽頁面滾動:
fixed用來控制是否懸停
/**
* 頁面滾動監(jiān)聽
*/
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
},
此時我們需要的效果就實現(xiàn)了:
sectionHeader懸浮.gif
這個有一個要注意的點,我們在使用swlectorQuery()的時候伏穆,獲取到的top是當前調(diào)用改函數(shù)時相應節(jié)點對應當前頂部的距離拘泞,這就有一個問題纷纫,當我們的header的高度(不一定是header只要是section-header上面的視圖的高度)發(fā)生變化的時候枕扫,懸停就會有問題,因為我們的高度是最開始的時候獲取的辱魁。
所以在我們改變高度之后烟瞧,要再次調(diào)用該函數(shù)去獲取距離"當前頂部"的距離,這也是要注意的一個點染簇,如果我能直接再次獲取并賦值参滴,發(fā)現(xiàn)還是有問題,就是因為此時獲取的top不是距離整個page頁面頂部锻弓,而我們監(jiān)聽的頁面滾動卻是砾赔,所以我們可以修改代碼如下:
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()
加上此時頁面滾動的距離,則能保證我們預期的效果出現(xiàn)G嘧啤1┬摹!杂拨!
賞我一個贊吧~~~