需求:左边的日期可以滚动,右侧的日历选择日期后,左侧自动滚动到所选的日期位置。
<scroll-view scroll-x="true" scroll-y="true" scroll-with-animation="true" style="margin-left: 6rpx; width: 650rpx; height: 90rpx" :scroll-into-view="dayToView">
<view style="width: 600rpx; display: flex">
<view v-for="(item, index) in dayList" :key="index" :id="'day-' + index">
<view class="dayTitle" :class="current == index ? 'select' : ''" @click="timeSelectd(item, index)">
<view style="display: flex; flex-direction: column; justify-content: center; width: 100%; height: 100%">
<view v-if="index == 0" style="font-size: 20rpx">今天</view>
<view v-else style="font-size: 20rpx">周{{ item.week }}</view>
<view v-if="current == index" style="font-size: 28rpx; font-weight: 500">{{ item.month }}/{{ item.day }}</view>
<view v-else style="font-size: 28rpx; font-weight: 500">{{ item.day }}</view>
</view>
</view>
</view>
</view>
</scroll-view>
js:
data() {
return {
dayToView: '',
},
timeSelectd(item, index) {
this.dayToView = 'day-' + index;
},
这段代码是项目中的业务逻辑,主要需要设置:scroll-into-view的="dayToView"。dayToView就是要滚动到的元素的位置。scroll-into-view 的值必须是动态的,通过setData设置后,重新渲染才会有效。如果是静态的,如scroll-into-view="item2",则无效。
scroll-view 必须有固定的高度,如果设置高度为百分比的话,父容器一定要固定高度,否则无效。比如最顶层的 view 没有设置固定高度,然后在下面添加的 scroll-view 的高度就直接设置height:100%是无效的,此时可以设置为height:100vh代替。