banner
banner
banner
NEWS LETTER

小程序自定义日历:横向滑动月历与行程

Scroll down

手写月历的核心只有一句:月初补空位、每 7 个切一行、行尾补空格。
补空位是为了让 1 号落在正确星期列,切行是为了让 WXML 能用两层 wx:for 渲染成网格,补空格是为了最后一行不至于缺格错位。
滑动部分是 scroll-view 的横向滚动 + scroll-into-view 定位到当前月,两个属性缺一个都会失效。

一、背景

这是一个自定义日历组件,components/customCalendar/customCalendar,需求拆开是四条:

  • 一次生成近一年(当前月前后各 6 个月)的月份数据,横向滑动切换;
  • 每月的 1 号要落在正确的星期列,周末换色;
  • 今天高亮成圆形,格子里能挂上当天的行程;
  • 点某一天,用 mark:day / mark:date 把「日」和「年月」透传出去。

数据全部由 dayjs 生成,组件本身不请求接口,行程由外部传入。

二、实现

2.1 生成近一年月份

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import dayjs from 'dayjs'

interface DayCell {
day: string
key: string
class?: string
color?: string
itinerary?: string[]
}

interface MonthItem {
time: string
list: { rowKey: string; cells: DayCell[] }[]
}

// 行程示例数据:真实项目由接口返回,这里只按日期分组便于演示
const itineraryMap: Record<string, string[]> = {
'2026-12-05': ['09:00 体检'],
'2026-12-18': ['14:00 面谈'],
}

function buildMonths(): { monthList: MonthItem[]; currentDate: string } {
const now = new Date()
const year = now.getFullYear()
const month = now.getMonth() // 0 ~ 11
const today = dayjs(now).format('YYYY-MM-DD')

const rawList: MonthItem[] = []
for (let i = -6; i <= 6; i++) {
// 用「年、月、日」三个数字构造:iOS 不认 new Date('2026-12') 这种纯年月字符串
const date = new Date(year, month + i, 1)
rawList.push({ time: dayjs(date).format('YYYY-MM'), list: [] })
}

const monthList = rawList
.sort((a, b) => a.time.localeCompare(b.time))
.map((item) => {
const [y, m] = item.time.split('-').map(Number) // m 是 1 ~ 12
const dayCount = new Date(y, m, 0).getDate() // 下个月第 0 天 = 本月最后一天
const weekIndex = new Date(y, m - 1, 1).getDay() // 1 号是星期几

const cells: DayCell[] = []
for (let d = 1; d <= dayCount; d++) {
const date = new Date(y, m - 1, d)
const key = dayjs(date).format('YYYY-MM-DD')
cells.push({
day: dayjs(date).format('DD'),
key,
class: key === today ? 'current' : '',
color: [0, 6].includes(date.getDay()) ? 'weekend-color' : '',
itinerary: itineraryMap[key] || [],
})
}

// 1 号之前补空位,保证日期落在正确的星期列
for (let j = 0; j < weekIndex; j++) {
cells.unshift({ day: '', key: `${item.time}-blank-${j}` })
}

// 每 7 个切一行,行尾补空格
const rows: { rowKey: string; cells: DayCell[] }[] = []
for (let i = 0; i < Math.ceil(cells.length / 7); i++) {
const line = cells.slice(7 * i, 7 * (i + 1))
while (line.length < 7) {
line.push({ day: '', key: `${item.time}-tail-${i}-${line.length}` })
}
rows.push({ rowKey: `${item.time}-row-${i}`, cells: line })
}

return { ...item, list: rows }
})

return { monthList, currentDate: today.slice(0, 7) }
}

2.2 组装与定位当前月

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Component({
data: {
month_list: [] as MonthItem[],
ScrollIntoView: '',
},

lifetimes: {
attached() {
const { monthList, currentDate } = buildMonths()
// 当前月在排序后的下标,不要写死成 6
const currentIndex = monthList.findIndex((item) => item.time === currentDate)
this.setData({
month_list: monthList,
ScrollIntoView: `list${currentIndex}`,
})
},
},

methods: {
getDate(e: any) {
const { day, date } = e.mark
if (!day) return // 空占位格不响应点击
wx.showToast({ title: `${date}-${day}`, icon: 'none' })
},
},
})

2.3 结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<scroll-view class="container-X" scroll-x scroll-with-animation scroll-into-view="{{ScrollIntoView}}">
<view class="calendar-container" id="list{{index}}" wx:for="{{month_list}}" wx:key="time">
<view class="calendar-title">{{item.time}}</view>
<view class="calendar-body-line" wx:for="{{item.list}}" wx:for-item="row" wx:key="rowKey">
<view
class="calendar-body-line-layout-date"
wx:for="{{row.cells}}"
wx:for-item="lineItem"
wx:key="key"
mark:day="{{lineItem.day}}"
mark:date="{{item.time}}"
bindtap="getDate"
>
<view class="day {{lineItem.class}} {{lineItem.color}}">{{lineItem.day}}</view>
<view class="calendar-body-itinerary-layout" wx:if="{{lineItem.itinerary.length}}">
<text wx:for="{{lineItem.itinerary}}" wx:for-item="plan" wx:key="*this">{{plan}}</text>
</view>
</view>
</view>
</view>
</scroll-view>

2.4 样式

横向滑动靠「父级 white-space: nowrap + 子项 inline-block + 子项宽度 100%」三件套;行程条绝对定位在日期格下方:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
.container-X {
white-space: nowrap;
}
.calendar-container {
display: inline-block;
width: 100%; // 必须是 100% + inline-block,否则月份会竖向堆叠
}
.calendar-body-line-layout-date {
position: relative;
display: inline-block;
width: 14.28%; // 100 / 7
text-align: center;
}
.calendar-body-itinerary-layout {
position: absolute;
top: 36rpx; // 浮在日期下方
left: 0;
display: flex;
flex-direction: column;
font-size: 18rpx;
}
.current {
border-radius: 50%;
background-color: rgba(15, 73, 0, 0.85);
color: #fff;
}
.weekend-color {
color: #d9534f;
}

三、踩坑与修正

  • scroll-x 要三件套一起写:scroll-view 上 scroll-x、父级 white-space: nowrap、子项 display: inline-block,少一个月份就变成竖向排列。
  • **scroll-into-view 的值是元素的 id**,不是类名,也不要带 #;id 里避免出现数字开头。
  • 月初补位与行尾补位缺一不可:只补月初,最后一行会缺格导致下一个月的 1 号顶上来;只补行尾,1 号会从周一列开始。
  • new Date('2026-12') 是 iOS 专属坑:只认 YYYY/MM/DD 或 ISO 带日的形式,纯年月请用「年、月、日」数字构造。
  • wx:for 里拿不到「上一层的 index」:原稿最内层想用 lineIndex 做 key,但外层 wx:for 没声明 wx:for-index,该变量根本不存在;嵌套循环取 index 要显式写 wx:for-index="xxx"。
  • 行程只在当前月渲染:原稿用 currentDate === item.time 做条件,非当前月的行程和周末配色都不会显示;要全月展示就得把条件去掉,改成按日期判断。

小结

  • 日期网格 = 月初空位填充 + 每 7 个一维切分 + 行尾补齐,这套算法与框架无关,课程表、排班表、预约日历都能直接套。
  • 涉及时区与格式的日期一定走 new Date(y, m, d) 或 dayjs 解析,字符串 new Date('2026-12') 在 iOS 上必翻车。
  • 嵌套 wx:for 的 wx:key 要落在真正唯一的字段上,没有就自己补一个(YYYY-MM-DD),空占位格也要给唯一的键。
  • 横向滑动与定位是两组属性:scroll-x 三件套负责「能滑」,scroll-into-view + 现算下标负责「滑到哪」。
其他文章
目录导航 置顶
  1. 1. 一、背景
  2. 2. 二、实现
    1. 2.1. 2.1 生成近一年月份
    2. 2.2. 2.2 组装与定位当前月
    3. 2.3. 2.3 结构
    4. 2.4. 2.4 样式
  3. 3. 三、踩坑与修正
  4. 4. 小结
请输入关键词进行搜索