<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Document</title>
<style>
#calendar {
display: flex;
flex-wrap: nowrap;
overflow-x: auto;
width: 100%;
}
section {
margin: 10px;
min-width: 300px;
}
h1 {
font-size: 18px;
}
table {
border-spacing: 0;
border-collapse: collapse;
width: 100%;
}
td {
border: 1px solid #ddd;
padding: 5px;
text-align: center;
}
td:first-child {
color: red;
}
td:last-child {
color: royalblue;
}
td.is-disabled {
color: #ccc;
}
td.today {
border: 4px solid #40BA8D;
}
td.special {
color: white;
background-color: orange;
}
</style>
</head>
<body>
<h1>Today is</h1>
<div id="calendar"></div>
<script>
const weeks = ['日', '月', '火', '水', '木', '金', '土'];
const date = new Date();
const year = date.getFullYear();
const today = date.getDate();
const currentMonth = date.getMonth();
const currentYear = date.getFullYear();
const month = date.getMonth() + 1;
const config = {
show: 3,
};
// 特定の日付をここで指定します
const specialDates = {
'2024-07-09': true,
'2024-07-22': true,
'2024-06-14': true
};
function showCalendar(year, month) {
for (let i = 0; i < config.show; i++) {
const calendarHtml = createCalendar(year, month);
const sec = document.createElement('section');
sec.innerHTML = calendarHtml;
document.querySelector('#calendar').appendChild(sec);
month++;
if (month > 12) {
year++;
month = 1;
}
}
}
function createCalendar(year, month) {
const startDate = new Date(year, month - 1, 1); // 月の最初の日を取得
const endDate = new Date(year, month, 0); // 月の最後の日を取得
const endDayCount = endDate.getDate(); // 月の末日
const lastMonthEndDate = new Date(year, month - 1, 0); // 前月の最後の日の情報
const lastMonthEndDayCount = lastMonthEndDate.getDate(); // 前月の末日
const startDay = startDate.getDay(); // 月の最初の日の曜日を取得
let dayCount = 1; // 日にちのカウント
let calendarHtml = ''; // HTMLを組み立てる変数
calendarHtml += '<h1>' + year + '年' + month + '月</h1>';
calendarHtml += '<table>';
// 曜日の行を作成
for (let i = 0; i < weeks.length; i++) {
calendarHtml += '<td>' + weeks[i] + '</td>';
}
for (let w = 0; w < 6; w++) {
calendarHtml += '<tr>';
for (let d = 0; d < 7; d++) {
if (w == 0 && d < startDay) {
// 1行目で1日の曜日の前
let num = lastMonthEndDayCount - startDay + d + 1;
calendarHtml += '<td class="is-disabled">' + num + '</td>';
} else if (dayCount > endDayCount) {
// 末尾の日数を超えた
let num = dayCount - endDayCount;
calendarHtml += '<td class="is-disabled">' + num + '</td>';
dayCount++;
} else {
// 特定の日付にクラスを付ける
const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(dayCount).padStart(2, '0')}`;
if (specialDates[dateStr]) {
calendarHtml += '<td class="special">' + dayCount + '</td>';
} else if (dayCount == today && month - 1 == currentMonth && year == currentYear) {
calendarHtml += '<td class="today">' + dayCount + '</td>';
} else {
calendarHtml += '<td>' + dayCount + '</td>';
}
dayCount++;
}
}
calendarHtml += '</tr>';
}
calendarHtml += '</table>';
return calendarHtml;
}
showCalendar(year, month);
</script>
</body>
</html>