以前兩篇文章分別介紹了錨點定位和滑動內容影響導航選中,這裏咱們就結合起來,實現這兩個功能!bash
思路再也不多說,直接上乾貨!微信
<view class="navigateBox">
<view class="title">
<image wx:if="{{actionView=='productBox'}}" src="../images/position.png"/>
<view class="title {{actionView=='productBox' ? 'checked':''}}" bindtap="toViewClick" data-hash="productBox">商品</view>
</view>
<view class="title">
<image wx:if="{{actionView=='commentBox'}}" src="../images/position.png"/>
<view class="title {{actionView=='commentBox' ? 'checked':''}}" bindtap="toViewClick" data-hash="commentBox">評價</view>
</view>
<view class="title">
<image wx:if="{{actionView=='infoBox'}}" src="../images/position.png"/>
<view class="title {{actionView=='infoBox' ? 'checked':''}}" bindtap="toViewClick" data-hash="infoBox">詳情</view>
</view>
</view>
<scroll-view style="height:{{winHeight}}" scroll-into-view="{{toView}}" scroll-y="true" bindscroll="scrollTo">
<view id="productBox" class="content">商品信息...</view>
<view id="commentBox" class="content">評價內容...</view>
<view id="infoBox" class="content">商品詳情...</view>
</scroll-view>
複製代碼
data: {
winHeight: '100%',
toView: 'productBox',//錨點跳轉的ID
actionView: 'productBox',//控制導航顯示
productBoxTop: 0,//商品模塊距離頂部的距離
commentBoxTop: 0,//評價模塊距離頂部的距離
infoBoxTop: 0,//詳情模塊距離頂部的距離
};
onLoad() {
let that = this;
wx.getSystemInfo({
success: function (res) {
//屏幕的寬度/屏幕的高度 = 微信固定寬度(750)/微信高度
that.setData({
winHeight = res.windowHeight-(res.windowWidth*90/750)+'px'
})
}
});
}
onShow() {
// 獲取各模塊距離頂部的距離
new Promise(resolve => {
let query = wx.createSelectorQuery();
query.select('#productBox').boundingClientRect();
query.select('#commentBox').boundingClientRect();
query.select('#infoBox').boundingClientRect();
query.exec(function (res) {
resolve(res);
});
}).then(res => {
this.setData({
productBoxTop: res[0].top,
commentBoxTop: res[1].top,
infoBoxTop: res[2].top
});
});
}
//錨點定位
toViewClick(e) {
this.setData({
toView: e.target.dataset.hash,
actionView: e.target.dataset.hash
})
},
scrollTo(e){
let scrollTop = e.detail.scrollTop+100; //滾動的Y軸
if(scrollTop >= this.infoBoxTop){
this.setData({
actionView: 'infoBox'
})
}else if(scrollTop >= this.commentBoxTop){
this.setData({
actionView: 'commentBox'
})
}else {
this.setData({
actionView: 'productBox'
})
}
//this.$apply();//WEPY更新數據
}
複製代碼
page {
height: 100%;
}
.navigateBox {
background: #fff;
height: 80rpx;
padding: 0 100rpx;
margin-bottom: 10rpx;
}
.navigateBox .title {
margin: 20rpx 46rpx;
float: left;
font-size: 27rpx;
width: 60rpx;
padding-left: 30rpx;
}
.navigateBox .title .right {
float: right;
margin-top: -5rpx;
}
.navigateBox image {
width: 30rpx;
height: 30rpx;
margin-left: -30rpx;
}
.navigateBox .checked {
color: #f73c3c;
}
.content {
height: 1000rpx;
}
複製代碼