如图所示,下面的scroll-view是横向滚动的,动态展示当天前后半个月的日期,需求是点击哪个日期就让谁选中并且居中显示,搞了快一天了才发现这个方法,下面分享给大家
到此结束,下面贴上源码
<!-- 日历 -->
<view class="classname" style="width:100%; height: 200rpx;">
<scroll-view :scroll-x = "true" scroll-with-animation="true" :scroll-left="scrollLeft" style="width:100%;height: 200rpx;white-space:nowrap;background: rgba(64, 151, 255, 0.08);">
<view class="calendar">
<view class="calendar_day" :class="{'calendar_days':item.itemed==nowDay}" @click="choseDay(item,index)" v-for="(item,index) in allArr" :key="index">
<text class="top">{{item.week}}</text>
<text class="bottom">{{item.dd}}</text>
</view>
</view>
</scroll-view>
</view>
data(){
return{
allArr:[],//循环的日历
scrollLeft: 50,
contentScrollW: 0, // 导航区宽度
}
},
onShow() {
this.allArr = [];
this.getNowDay(this.nowDay);//获取当前日期 年月日
this.calculationList(); //目的为了循环列表
this.scrollLeft = 680
},
mounted() {
// 获取标题区域宽度,和每个子元素节点的宽度
this.getScrollW()
},
methods:{
// 获取标题区域宽度,和每个子元素节点的宽度以及元素距离左边栏的距离
getScrollW() {
const query = uni.createSelectorQuery().in(this);
console.log(query,'queryqueryquery');
query.select('.classname').boundingClientRect(data => {
// 拿到 scroll-view 组件宽度
this.contentScrollW = data.width
}).exec();
query.selectAll('.calendar_day').boundingClientRect(data => {
let dataLen = data.length;
for (let i = 0; i < dataLen; i++) {
// scroll-view 子元素组件距离左边栏的距离
this.allArr[i].left = data[i].left;
// scroll-view 子元素组件宽度
this.allArr[i].width = data[i].width
}
}).exec()
},
choseDay(item,index){ //点击选中的时间
console.log(item,'选中的年月日')
this.nowDay = item.itemed;
this.nowMon =item.mm;
// 当前点击子元素距离左边栏的距离 - scroll-view 宽度的一半 + 当前点击子元素一半的宽度 实现居中展示
this.scrollLeft = this.allArr[index].left - this.contentScrollW / 2 + this.allArr[index].width / 2;
//然后在下面的操作去请求接口
}
}
OK,结束了,困扰一天的需求终于搞定了,迫不及待的想分享给有需要的人