1、錨點按鈕
data-* 的值對應要跳轉的錨點的id值
2、點擊按鈕時,將toView的值設置為當前點擊的按鈕的data-*的值(一定要用setData方法,不能直接用this.toView=... ,不然頁面的值無法改變)
3、給需要跳轉的內容外加上<scroll-view ></scroll-view>
scroll-into-view的值為需要跳轉到的位置的id值
scroll-y:是否為垂直滾動
scroll-with-animation:是否加滾動動畫效果
tips:
1、page設置高度為100%;
2、必須設置scroll-view的高度(我設置的為設備的高)
以下為點擊跳轉錨點的完整代碼
<!--pages/test/test.wxml--> <view class="menu"> <view class='item {{nowstatus == "productBox" ? "on" : ""}}' bindtap="toViewClick" data-hash="productBox">商品</view> <view class='item {{nowstatus == "commentBox" ? "on" : ""}}' bindtap="toViewClick" data-hash="commentBox">評論</view> <view class='item {{nowstatus == "infoBox" ? "on" : ""}}' bindtap="toViewClick" data-hash="infoBox">詳情</view> </view> <scroll-view class="box" style="height:{{winHeight}}" scroll-into-view="{{toView}}" scroll-y="true" scroll-with-animation="true"> <view id="productBox">商品圖</view> <view id="commentBox">評論部分</view> <view id="infoBox">詳情部分</view> </scroll-view>
// pages/test/test.js Page({ data: { winHeight:'100%', toView:'productBox', nowstatus:'productBox' }, onLoad: function (options) { let that=this; wx.getSystemInfo({ success: function(res) { that.setData({ winHeight: res.windowHeight - (res.windowWidth * 90 / 750) + 'px' }) }, }) }, toViewClick:function(e){ this.setData({ toView: e.target.dataset.hash, nowstatus: e.target.dataset.hash }) } })
/* pages/test/test.wxss */ page{ height:100%; } .box{height:100%; margin-top:60rpx;} .box view{ height:1500rpx; text-align: center; } .menu{ display: flex; background:#fff; padding:40rpx 0 10rpx 20%; } .menu .item{ width:20%; line-height: 80rpx; color:#333; text-align: center; } .menu .item.on{ color:red; border-bottom:2px solid red; }
{
"navigationStyle": "custom"
}
----------------------------------------- 滑動時相應的tab高亮顯示 --------------------------------------------------
1、獲取每個部分距頂部的高度
onLoad: function (options) { let that=this; let query = wx.createSelectorQuery(); query.select('#commentBox').boundingClientRect(res => { //獲取評論距離頁面頂部高度 that.setData({ commentBoxTop: res.top }) }).exec() query.select('#infoBox').boundingClientRect(res => { //獲取詳情部分距離頁面頂部高度 that.setData({ infoBoxTop: res.top }) }).exec() }
2、監聽當前滑動
3、對比當前滑動的距離和每個部分距頂部的高度
onPageScroll: function (e) { var that=this; console.log(that.data.infoBoxTop) console.log(e.detail.scrollTop) if (e.detail.scrollTop <= that.data.commentBoxTop - 80){ that.setData({ nowstatus: 'productBox' }) } if (e.detail.scrollTop > that.data.commentBoxTop -80){ that.setData({ nowstatus:'commentBox' }) } if (e.detail.scrollTop > that.data.infoBoxTop - 80){ console.log("true") that.setData({ nowstatus: 'infoBox' }) } }