很多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.setData({
-
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()
加上此時頁面滾動的距離,則能保證我們預期的效果出現!!!!
|