很多APP都有這么一個效果,列表頭在滾動到頂部時會懸停在頂部,比如在iOS開發(fā)中UITableview設(shè)置 style 屬性設(shè)置為 Plain ,這個tableview的section header在滾動時會默認(rèn)懸停在界面頂端。
那么我們怎么在微信小程序也實(shí)現(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é)點(diǎn)并拿到該節(jié)點(diǎn)此時距離當(dāng)前頂部的距離
注意是 此時,這個后面再講
-
/**
-
* 頁面加載完成
-
*/
-
onReady: function () {
-
let that = this
-
let query = wx.createSelectorQuery()
-
query.select(".section-header").boundingClientRect(function (res) {
-
// console.log(res)
-
that.setData({
-
//section header 距離 ‘當(dāng)前頂部’ 距離
-
sectionHeaderLocationTop: res.top
-
})
-
}).exec()
-
},
2、我們需要監(jiān)聽頁面滾動:
fixed用來控制是否懸停
-
/**
-
* 頁面滾動監(jiān)聽
-
*/
-
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
-
})
-
}
-
},
3、修改相應(yīng)的樣式:
將原來的header修改為如下代碼,并添加一個placeholder視圖,目的是當(dāng)我們的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 距離 ‘當(dāng)前頂部’ 距離
-
sectionHeaderLocationTop: 0,
-
//頁面滾動距離
-
scrollTop: 0,
-
//是否懸停
-
fixed: false
-
},
此時我們需要的效果就實(shí)現(xiàn)了:

sectionHeader懸浮.gif 這個有一個要注意的點(diǎn),我們在使用swlectorQuery()的時候,獲取到的top是當(dāng)前調(diào)用改函數(shù)時相應(yīng)節(jié)點(diǎn)對應(yīng)當(dāng)前頂部的距離,這就有一個問題,當(dāng)我們的header的高度(不一定是header只要是section-header上面的視圖的高度)發(fā)生變化的時候,懸停就會有問題,因為我們的高度是最開始的時候獲取的。
所以在我們改變高度之后,要再次調(diào)用該函數(shù)去獲取距離"當(dāng)前頂部"的距離,這也是要注意的一個點(diǎn),如果我能直接再次獲取并賦值,發(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 距離 ‘當(dāng)前頂部’ 距離
-
sectionHeaderLocationTop: res.top + that.data.scrollTop
-
})
-
}).exec()
加上此時頁面滾動的距離,則能保證我們預(yù)期的效果出現(xiàn)!!!!
|