仿美团外卖商品分类功能,点击元素会自动滚动到当前容器的中间位置。
效果:
701_1723183953
代码:
HTML:
<view class="class-view">
<scroll-view class="class-left" scroll-y="true" :scroll-top="newScrollTop" :scroll-with-animation="true">
<text class="class-left-item" v-for="item,index in tag_list" :key="index" @click="select(index, item)"
:class="test == index ? 'active_left' : ''">{{ item.tag_name }}</text>
</scroll-view>
<view class="class-right">
<view @click="nav_details(item.id)" v-for="item,index in game_list" :key="index">
<image :src="item.icon" mode=""></image>
<view>
<text>{{ item.game_name }}</text>
<text>{{ item.resh_tag }}</text>
</view>
</view>
</view>
</view>
JS:
export default {
data() {
return {
test: 0,
tag_list: [], // 分类标签数组
newScrollTop: 0
}
},
methods: {
select(index, item) {
this.test = index;
const query = uni.createSelectorQuery().in(this);
query.selectAll('.class-left-item').boundingClientRect((rects) => {
const containerHeight = uni.getSystemInfoSync().windowHeight;
const itemTop = rects[index].top;
const itemHeight = rects[index].height;
const containerTop = rects[0].top;
// 计算新滚动条的位置,使选中项在可视区域居中
this.newScrollTop = itemTop - containerTop + (itemHeight / 2) - (containerHeight / 2);
console.log(this.newScrollTop);
}).exec();
},
}
}
CSS:
.class-view {
display: flex;
// 左侧分类列表容器
.class-left {
height: 100vh;
width: 25%;
background: #f1f1f1;
display: flex;
align-items: center;
flex-direction: column;
overflow-y: scroll;
.class-left-item {
color: #333;
display: block;
width: 100%;
height: 100rpx;
font-size: 32rpx;
line-height: 100rpx;
text-align: center;
}
}
// 右侧选中分类后需要展示的数据
.class-right {
height: 100vh;
width: 75%;
overflow-y: scroll;
}
}
// 选中当前元素添加的样式
.active_left {
color: #000 !important;
font-size: 34rpx !important;
font-weight: 550 !important;
background: #fff !important;
}