微信小程式導航吸頂操作
阿新 • • 發佈:2020-12-31
問題:
製作可以隨頁面滑動的導航,滑到頂端就掛在頂部,下滑時回根據頁面的調整下滑。通過頁面監聽來控制導航的定位樣式。
方案:
節點:監聽標記 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
})
},