image.png
聯動效果.gif
通過點擊左側菜單選項卡,右側內容區域滾動到對應的高度位置,同樣,右側內容區域滾動一定的距離后,左側選項卡需要判斷右側內容是屬于左側哪個選項卡的內容。
1、左側菜單點擊事件的處理
- data選項數據為:
data() {
return {
cateList: [], //左側分類列表
current: 0, //當前點擊項
rectInfoList:[],
tempCurrent:0,
scrollTop:0,//左側導航欄距離頂部的位置
}
},
- 左側菜單使用scroll-view渲染
<!-- 左側菜單選項 -->
<scroll-view :scroll-top="scrollTop" class="cate-left" scroll-y="true" show-scrollbar="false">
<view class="cate-item" :class="{active:current==index}" v-for="(item,index) in cateList" @click="menuTab(index)"
:key="item.id">
{{item.catename}}
</view>
</scroll-view>
通過動態類樣式完成將current
值與index
索引綁定,以及通過menuTab
將index索引下標值作為參數傳入。
添加scroll-top
屬性,每次切換菜單,都讓滾動條與頂部保持一定的距離
2、右側內容區域通過uni.createSelectorQuery()獲取元素盒子的高度值
- 右側內容區域
<!-- 右側對應的商品展示 -->
<view class="cate-right">
<scroll-view :scroll-into-view="'cate'+tempCurrent" class="cate-right-scroll" scroll-y="true" show-scrollbar="false" @scroll="getCurrentHeight">
<view :id="'cate'+index" v-for="(item,index) in cateList" :key="item.id" class="cate-right-item">
<view class="cate-title">
--<text>{{item.catename}}</text>--
</view>
<view v-for="(el,index) in item.product" :key="el.id" class="cate-right-img">
<image :src="imgUrl + el.mainimage"></image>
<text>{{el.smalltitle}}</text>
</view>
</view>
<view style="height: 30rpx;"></view>
</scroll-view>
</view>
- 獲取不同的id值的高度
與H5類似,通過id選擇器去獲取元素的寬,高的詳細信息,一開始top
為0,高度值賦給bottom
,然后下一次就變為上一個元素的bottom
值就是下一個元素的top
值,遍歷完成后,把值整個存在一個數組中,作為對象數組進行存儲。
- 獲取不同的id值的高度
// 獲取與頂部之間的距離
getRectInfo() {
var top = 0;
var bottom = 0;
var temp = 0;
for (var i = 0; i < this.cateList.length; i++) {
let view = uni.createSelectorQuery().in(this).select("#cate"+i);
view.fields({
size: true,
rect: true
}, data => {
top = temp;
bottom = top + data.height;
temp = bottom;
this.rectInfoList[i] = {
'top':top,
'bottom':bottom
}
// console.log(top, bottom);
}).exec();
}
console.log(this.rectInfoList);
},
3、右側內容區滑動時判斷對應的左側索引下標值
當右側滑動內容時,需要使用@scroll
事件綁定在scroll-view
上,然后e.detail.scrollTop
獲取到的就是當前內容距離頂部之間的距離,通過拿到這個距離,再去與存儲在數組中的每個模塊的top
,bottom
值去匹配,如果currentHeight
(也就是當前的距離頂部的高度)滿足其中的范圍,那么就將對應的index
索引賦值到左側菜單上去。
image.png
getCurrentHeight(e){
var currentHeight = e.detail.scrollTop;
this.rectInfoList.forEach((item,index)=>{
if(currentHeight >= item.top && currentHeight <= item.bottom){
// 當前獲取的盒子高度大于top小于bottom,判定將索引傳至左側菜單導航
this.current = index;
this.scrollTop = index * uni.upx2px(100);
}
})
}
4、清空默認的滾動條
想要清空默認的滾動條,在scroll-view
中需要加入show-scrollbar="false"
以及在對應的style樣式中去加入樣式代碼。
/deep/::-webkit-scrollbar {
display: none;
width: 0;
height: 0;
}
5、注意點
值得一提的是getRectInfo
函數需要在dom
樹渲染完成后才可以進行調用,否則dom
樹還未生成,獲取到的信息是null
,因此,需要使用一個定時器去異步調用。并且該方法只能在mounted
生命周期中去使用。
mounted() {
setTimeout(() => {
this.getRectInfo();
}, 200)
},