2025-01-12 JavaScript 系列八:第4課 ── 行事曆應用程式-步驟03

2025-01-12 JavaScript 系列八:第4課 ── 行事曆應用程式-步驟03

點日期 ,然後在日期的那一格 顯示 新增活動的按鈕

好,來~我們分步驟做:

目標:點月曆中的某一天,在那一天的格子中出現「新增活動」按鈕。


🔧 1. 修改 FullCalendar 的設定

FullCalendar 提供 dateClick 事件,當使用者點某個日期時會觸發,我們就用這個來動態插入按鈕。


✨ 修改後的 Calendar.vue

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
<template>
<div>
<h2>我的行事曆</h2>
<div ref="calendarRef" id="calendar"></div>
</div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const calendarRef = ref(null)

onMounted(() => {
if (window.FullCalendar && window.FullCalendar.Calendar) {
const calendar = new window.FullCalendar.Calendar(calendarRef.value, {
initialView: 'dayGridMonth',
locale: 'zh-tw',
events: [
{
title: '測試活動',
start: new Date().toISOString().split('T')[0],
}
],
dateClick: function (info) {
// 移除之前的按鈕
document.querySelectorAll('.add-event-button').forEach(btn => btn.remove())

// 找到被點的 cell
const cellEl = info.dayEl

// 建立按鈕
const button = document.createElement('button')
button.textContent = '新增活動'
button.className = 'add-event-button'
button.style.marginTop = '5px'
button.style.fontSize = '12px'

// 加入 click 功能(可以彈出視窗、打開表單...)
button.onclick = () => {
alert(`你點了 ${info.dateStr},這裡可以打開活動編輯表單!`)
}

// 加到 cell 裡面
cellEl.appendChild(button)
}
})

calendar.render()
} else {
console.error('FullCalendar 尚未載入,請檢查 index.html CDN script。')
}
})
</script>

<style scoped>
#calendar {
max-width: 800px;
margin: 20px auto;
}
.add-event-button {
background-color: #007bff;
color: white;
border: none;
padding: 2px 6px;
border-radius: 4px;
cursor: pointer;
}
</style>

🧪 測試方式

  1. 開啟你的頁面
  2. 點任一天的格子
  3. 那一格底下會出現「新增活動」按鈕
  4. 點按鈕會彈出 alert(之後可改成打開 datetimepicker 或輸入框)

下一步想做什麼?我可以幫你接上表單、時間選擇器、或讓活動存進 localStorage~你決定😄