y開始使用的解決方案是使用聚堆定位,在onShow中獲取元素距離頂部的距離,然后監聽頁面滾動,當滾動的距離大於距離頂部的距離時就讓他絕對定位
Page({
data: {
// 區域里頂部的距離吧
fixTop: 0,
// 滾動的距離
scrollTop: 0,
isFixed: false
},
onShow() {
let self = this
wx.createSelectorQuery().select('#bars').boundingClientRect(function(rect) {
if(rect && rect.top > 0){
self.setData({
fixTop: parseInt(rect.top)
})
}
}).exec()
},
onPageScroll (e) {
let isFixed = e.scrollTop >= this.data.fixTop ? true : false;
if(this.data.scrollTop === this.data.fixTop){
return false
}
this.setData({
isFixed,
})
}
})


這樣可以實現吸頂效果,但是會有問題,滾動的時候會抖動得特別厲害,解決的方法是是用粘性布局:

