微信小程序 简单的实现左右内容联动
实现方法
scroll-view
的属性scroll-into-view
可以实现类似于瞄点链接的效果,在绑定的属性修改时会触发,滑动到对应id的地方
注意: id不能以数字开头
设置两个变量tabIndex
、nowIndex
保存状态,如果只设置一个更新变量时会触发瞄点更新
通过tabIndex
更新瞄点
通过nowIndex
设置当前的分类(用来高亮当前的分类)
在按下分类时同时更新tabIndex
、nowIndex
在滑动时通过判断没一个id的内容距离scroll-view
顶部的高度
如果等于或小于0表示该内容滑到了,只需要 更新nowIndex
,如果更新`tabIndex了的话,会触发滑动
WXML
<view class="main">
<scroll-view class="category" scroll-with-animation
scroll-into-view="scroll-{{nowIndex}}"
scroll-y>
<view wx:for="{{ list }}" wx:key="index"
id="scroll-{{ index }}"
class="item {{ nowIndex==index?'active':'' }}" data-index="{{ index }}"
bindtap="tabNav">
{{ item.name }}
</view>
</scroll-view>
<scroll-view id="scrollMenu" class="menu" scroll-with-animation scroll-y scroll-into-view="{{tabIndex}}" bindscroll="scroll">
<view wx:for="{{ list }}" wx:key="index"
class="goodItem"
id="scroll-{{index}}">
<view class="title"> {{ item.name }}</view>
<view wx:for="{{item.food}}" wx:key="indexs" class="item" wx:for-index="indexs" wx:for-item="items">
<view class="left">
<image src="{{ items.image_url }}" mode="widthFix" />
</view>
<view class="right">
<view class="msg">
<view class="name">{{ items.name }}</view>
<view class="price">¥{{ items.price }}</view>
</view>
<view bindtap="addCarList" class="btn">
+
</view>
</view>
</view>
</view>
</scroll-view>
</view>
js
import api from '../../../utils/api/index';
Page({
data: {
list:[],
carList:[],
tabIndex:"scroll-0",
nowIndex:0
},
onLoad(options) {
this.getList()
},
getList(){
api.getFoodList().then(res=>{
this.setData(res)
})
},
tabNav(e){
let index = e.currentTarget.dataset.index
this.flag = true
this.setData({nowIndex:index})
this.setData({tabIndex:`scroll-${index}`})
},
addCarList(e){
this.data.carList.push(e)
this.setData({carList:this.data.carList})
},
scroll(e){
if(this.flag){
this.flag = false
return
}
var index = this.data.nowIndex
var scrollMenuTop = 0
let query = wx.createSelectorQuery()
query.selectAll('#scrollMenu').boundingClientRect()
query.selectAll('.goodItem').boundingClientRect()
query.exec(res=>{
console.log(res);
scrollMenuTop = res[0][0].top
res[1].forEach((item,index2) => {
if(item.top-scrollMenuTop<=0){
index = index2
}
});
this.setData({nowIndex:index})
})
}
})
效果图