微信小程序导航吸顶操作

问题:

制作可以随页面滑动的导航,滑到顶端就挂在顶部,下滑时回根据页面的调整下滑。通过页面监听来控制导航的定位样式。

方案:

节点:监听标记 id = ‘nav’

<view class='list-card' id='nav'>
  <view class="nav-card {
     
     {isTop?'top-fix':''}}">
     <view class="nav-item {
     
     {index==navIndex?'nav-active':''}}"
           bindtap="changeNav"
           id='{
     
     {index}}'
           wx:for='{
     
     {nav}}'
           wx:key='index'>
           <view>{
   
   {item.title}}</view>
           <text>{
   
   {item.tip}}</text>
     	</view>
    </view>
	<view hidden="{
     
     {!isTop}}" class='line-block'></view>
</view>

样式:

在这里插入图片描述
吸顶样式

.top-fix{
    
    
    position: fixed;
    left: 0;
    right: 0;
    top: 76rpx;
    background-color: #fff;
    z-index: 9;
}

导航样式

.line-block{
    
    
    width: 100%;
    height: 116rpx;
}
.nav-card{
    
    
    padding: 20rpx;
    display: flex;
    align-items: center;
    transition: all 0.2s ease-in-out;
}
.nav-item{
    
    
    width: 25%;
    text-align: center;
}
.nav-item>view{
    
    
    font-size: 30rpx;
    font-weight: bold;
}
.nav-item>text{
    
    
    font-size: 22rpx;
    color: #999;
}
.nav-active{
    
    
    color:  #56ab2f!important;
}
.nav-active>text{
    
    
    color:  #a8e063!important;
}

页面监听标记点id=‘nav’

 // 页面滑动-导航滑动监听 rect.top到顶的距离,42px,因为顶部有搜索框,所以设为距顶42px
onPageScroll: function (e) {
    
    
  let query = wx.createSelectorQuery();
  query.select('#nav').boundingClientRect((rect) => {
    
    
    if (!this.data.isTop&&rect.top<=42){
    
    
      this.setData({
    
     isTop: true});
    } 
    if (this.data.isTop&&rect.top>42) {
    
    
      this.setData({
    
     isTop: false});
    }
  }).exec()
},

获取导航所做高度,用做没有吸顶时点击导航或切换吸顶

// 动态获取导航所在高度 /navTopHeight 全局变量
getNavToTopHeight() {
    
    
  let query = wx.createSelectorQuery();
  query.select('#nav').boundingClientRect((rect) => {
    
    
    if (rect) navTopHeight = rect.top - 41;
  }).exec()
},

导航切换并吸顶

// 导航切换
changeNav(e) {
    
    
  this.setData({
    
    navIndex: e.currentTarget.id});
  wx.pageScrollTo({
    
    
    scrollTop: navTopHeight,
    duration: 200
  })
},

猜你喜欢

转载自blog.csdn.net/qq_1296888290/article/details/112000290