功能需求:让 scroll-view组件自动定位到当前月份,比如11月。
效果图:
代码:
<template>
<view>
<scroll-view scroll-x enable-flex :scroll-into-view="scrollIndex" class="scrollCon">
<view class="monthItem" :class="item.value == month ? 'active':''" v-for="(item, index) in monthList"
:key="index" :id="'scroll'+index" @click="monthClick(index)">
<view class="monthNum">{{item.name}}</view>
</view>
</scroll-view>
</view>
</template>
<script>
export default {
data() {
return {
// 月份列表
monthList: [{
value: 1,
name: '1月',
}, {
value: 2,
name: '2月',
}, {
value: 3,
name: '3月',
}, {
value: 4,
name: '4月',
}, {
value: 5,
name: '5月',
}, {
value: 6,
name: '6月',
}, {
value: 7,
name: '7月',
}, {
value: 8,
name: '8月',
}, {
value: 9,
name: '9月',
}, {
value: 10,
name: '10月',
}, {
value: 11,
name: '11月',
}, {
value: 12,
name: '12月',
}],
// 年
year: '',
// 月
month: '',
// 定位当前月份
scrollIndex: '',
}
},
onLoad(option) {
},
onShow() {
},
onReady() {
var _this = this;
_this.getYearMonth();
},
methods: {
// 获取当前年月
getYearMonth() {
var _this = this;
var timestamp = Date.parse(new Date());
var date = new Date(timestamp);
//年
var Y = date.getFullYear();
//月
var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
_this.year = Y;
_this.month = M;
_this.scrollIndex = 'scroll' + date.getMonth(); //定位到当前月份
},
// 点击月份
monthClick(index) {
var _this = this;
_this.month = _this.monthList[index].value;
_this.scrollIndex = 'scroll' + index;
},
}
}
</script>
<style scoped>
/* 月模式 */
.scrollCon {
white-space: nowrap;
}
.monthItem {
display: inline-block;
width: 64rpx;
height: 64rpx;
margin-right: 50rpx;
}
.monthItem:last-child {
margin-right: 0;
}
.monthNum {
width: 64rpx;
height: 64rpx;
line-height: 64rpx;
text-align: center;
color: #3D3D3D;
font-size: 26rpx;
background: transparent;
border-radius: 50%;
overflow: hidden;
}
.monthItem.active .monthNum {
color: #fff;
background: #3662EC;
}
</style>
scroll-view横向滚动的核心css
scroll-view的内层view元素需要
display: inline-block;
scroll-view的外层元素需要
white-space: nowrap;