需求: 最終實(shí)現(xiàn)效果為頁(yè)面向上滾動(dòng)隱藏頂部分類菜單,向下滾動(dòng)則顯示頂部菜單
實(shí)現(xiàn)方法參考網(wǎng)上的方式自己改了一下
html
<view id="fix-view" animation='{{menuAnim}}'></view>
css
#fix-view {
width: 100%;
position: fixed;
top: 0;
left: 0;
z-index: 2;
background-color: #fff;
}
使用方法
// 頁(yè)面加載
onLoad(options) {
onScrollDom('#fix-view',this)
},
/**
* 生命周期函數(shù)--頁(yè)面滾動(dòng)
* @param event 滾動(dòng)對(duì)象信息
*/
onPageScroll: function (event) {
onScrollWindow(event,this)
},
封裝后的方法
/**
* 滾動(dòng)元素高度
* @param id 元素選擇器
* @param self 綁定this對(duì)象
*/
const onScrollDom = (id,self,options={}) =>{
wx.createSelectorQuery().select(id).boundingClientRect(function(rect) {
self.setData({
menuHeight: options.height || rect.bottom
})
}).exec()
}
/**
* 計(jì)算滾動(dòng)距離
* @param event 滾動(dòng)元素
* @param self 綁定this對(duì)象
*/
const onScrollWindow = (event,self) =>{
let scroll = event.scrollTop; //當(dāng)前的距離頂部的高度
let scrollTop = self.data.scrollTop; //記錄的距離頂部的高度
let height = self.data.menuHeight; //菜單的高度
let show = self.data.showMenu; //菜單的顯示狀態(tài)
//是否超過(guò)開(kāi)始隱藏的高度
if (scroll > height) {
if ((scroll < scrollTop) == show) { //超過(guò)高度時(shí)的上滑或下滑狀態(tài)一致時(shí)
self.setData({
scrollTop: scroll
})
} else { //超過(guò)高度時(shí)的上滑顯示和下滑隱藏
let anim = wx.createAnimation({
timingFunction: 'ease-in-out',
duration: 200,
delay: 0
})
anim.translateY(scroll < scrollTop ? 0 : -height).step();
self.setData({
scrollTop: scroll,
showMenu: scroll < scrollTop,
menuAnim: anim.export()
})
}
} else {
//小于menuHeight并且隱藏時(shí)執(zhí)行顯示的動(dòng)畫(huà)
if (!show) {
let anim = wx.createAnimation({
timingFunction: 'ease-in-out',
duration: 200,
delay: 0
})
anim.translateY(0).step();
self.setData({
scrollTop: scroll,
showMenu: true,
menuAnim: anim.export()
})
} else {
self.setData({
scrollTop: scroll
})
}
}
}
注意事項(xiàng)
- 如果存在fixed 嵌套fixed穷当,會(huì)導(dǎo)致嵌套的fixed失效,原因是 transform 導(dǎo)致饭耳,提供一種解決方式,在一定觸發(fā)條件下把 transform設(shè)置為空值 代碼
// 兼容fixed嵌套fixed問(wèn)題
let anim = wx.createAnimation({
timingFunction: 'ease-in-out',
duration: 200,
delay: 0
})
anim.translate('').step();
this.setData({
menuAnim:anim.export()
})