1、HTML
<view class="title {{isFixedTop?'title-fixed':''}}" id="navbar">
<view class="title-txt">
<view>第一</view>
<view>第二</view>
</view>
</view>
<view class="title" wx:if="{{isFixedTop}}"></view>
2、css
.title{
width: 100%;
display: flex;
justify-content: space-around;
box-sizing: border-box;
padding: 28rpx 0 28rpx 0;
background-color: #f4f4f4;
}
/* 吸顶 */
.title-fixed{
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 10;
background-color: #ffffff;
}
3、js
Page({
data: {
// 导航栏初始化距顶部的距离
navbarInitTop: 300,
// 是否固定顶部
isFixedTop: false,
},
onShow: function () {
// 吸顶
let that =this;
if(that.data.navbarInitTop==0){
// 获取节点距离顶部的距离
wx.createSelectorQuery().select("#navbar").boundingClientRect(function(rect){
if(rect && rect.top>0){
let navbarInitTop=parseInt(rect.top);
that.setData({
navbarInitTop:navbarInitTop
});
}
}).exec();
}
},
// 监听页面滑动事件
onPageScroll:function(e){
let that=this;
let scrollTop = parseInt(e.scrollTop); //滚动条距离顶部高度
//判断'滚动条'滚动的距离 和 '元素在初始时'距顶部的距离进行判断
let isSatisfy = scrollTop > that.data.navbarInitTop ? true : false;
that.setData({
isFixedTop: isSatisfy
});
},
})