之前有个小程序项目需要做一个导航栏吸顶的需求
个人理解:主要通过小程序方法onPageScroll(页面滚动事件)来做,当滚动距离顶部高度大于设定高度的时候显示固定定位的导航栏
记录一下
1.先要计算出页面滚动条滚动到哪里才弹出导航栏
wx.createSelectorQuery()文档链接地址
onLoad: function (options) {
let that = this;
//获取屏幕高度 预留胶囊高度
//wx.createSelectorQuery()返回一个获取DOM实例化对象如果是组件里面就需要用this.createSelectorQuery()
const query = wx.createSelectorQuery();
query.select('.line').boundingClientRect(function (res) {
console.log(res)
//获取边界线离顶部的距离
that.setData({
lineTop: res.top
})
}).exec();
},
2.小程序滚动时候会触发onPageScroll事件
// 吸顶效果(渐入渐出动画)onPageScroll:页面滚动距离顶部的距离高度触发事件
// isOne参数放data保证滚动时只触发一次
onPageScroll: function (event) {
let that = this;
console.log(event)
if (event.scrollTop > that.data.lineTop && that.data.isOne) {
//设置渐入动画 wx.createAnimation()创建动画实例
var animation = wx.createAnimation({
//动画持续事件 默认为400
duration: 500,
//动画实现效果 默认为linear
timingFunction: "ease",
//动画延迟时间
delay: 200
})
animation.translateY(200).step()
that.setData({
animationData: animation.export(),
isOne: false,
})
} else if(event.scrollTop < that.data.lineTop) {
var animation = wx.createAnimation({
duration: 500,
timingFunction: "ease",
delay: 200
})
animation.translateY(0).step()
that.setData({
animationData: animation.export(),
isOne: true,
})
}
},
3.wxml代码及css代码
<view class="big_box">
<view class="fixed_box" animation="{{animationData}}"></view>
<view class="head_box"></view>
<view class="line"></view>
</view>
.big_box{
height: 3000rpx;
width: 100%;
}
.head_box{
width: 100%;
height: 400rpx;
background-color: bisque;
}
.fixed_box{
position:fixed;
width: 750rpx;
height: 200px;
background-color: skyblue;
top: -200px;
}
.line{
width: 100%;
height: 2rpx;
background-color: slateblue;
}
4.缺陷和总结
一般吸顶用wx:if 控制显示隐藏,这里是我想写个简单动画,其实写动画是不太好的,因为动画translateY()平移单位是px,而小程序自适应单位为rpx,如果是顶部渐入盒子的话,盒子高度以及固定定位top高度应该用px为单位(不用px会出现白条或者内容展示不全问题),使用px就会和UI会有偏差。
希望能帮到大家,也便于自己记录(如果有帮助到大家可以点下赞哦~)!!!
如有疑问或者不对的地方可以下方评论留言讨论哦~会积极回复大家的!!!