IT/HTML
[HTML] 동기화 달력
잿호
2023. 10. 6. 04:36

설계
1. 일반적인 2차원 배열 구조의 달력이다.
2. Date() 함수를 통해 실시간으로 날짜와 동기되어 보여진다.
3. 현재 일에 해당되는 일자 칸을 하이라이트 시켜준다.
코드
<!DOCTYPE html>
<html lang="kr">
<head>
<meta charset="UTF-8">
<title>달력</title>
<style>
table {
border-collapse: collapse;
width: 300px;
margin: 0 auto;
}
h1 {
text-align: center;
}
#month {
text-align: center;
}
th, td {
text-align: center;
padding: 5px;
border: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}
.today {
background-color: #a9a9a9;
}
</style>
</head>
<body>
<h1>달력</h1>
<div id="month"></div>
<div id="calendar"></div>
</body>
<script>
function createCalendar(year, month) {
const daysInMonth = new Date(year, month + 1, 0).getDate();
const firstDay = new Date(year, month, 1).getDay();
const calendarDiv = document.getElementById("calendar");
const table = document.createElement("table");
const thead = document.createElement("thead");
const tbody = document.createElement("tbody");
const daysOfWeek = ["일", "월", "화", "수", "목", "금", "토"];
const tr = document.createElement("tr");
for (let i = 0; i < 7; i++) {
const th = document.createElement("th");
th.textContent = daysOfWeek[i];
tr.appendChild(th);
}
thead.appendChild(tr);
let dayCounter = 1;
for (let i = 0; i < 6; i++) {
const tr = document.createElement("tr");
for (let j = 0; j < 7; j++) {
const td = document.createElement("td");
if (i === 0 && j < firstDay) {
td.textContent = "";
} else if (dayCounter <= daysInMonth) {
td.textContent = dayCounter;
dayCounter++;
const currentDate = new Date();
if (
year === currentDate.getFullYear() &&
month === currentDate.getMonth() &&
parseInt(td.textContent) === currentDate.getDate()
) {
td.classList.add("today");
}
}
tr.appendChild(td);
}
tbody.appendChild(tr);
if (dayCounter > daysInMonth)
break;
}
table.appendChild(thead);
table.appendChild(tbody);
calendarDiv.appendChild(table);
const monthDiv = document.getElementById("month");
monthDiv.textContent = `${month + 1}월`;
monthDiv.classList.add("month");
monthDiv.appendChild(monthDiv);
}
const currentDate = new Date();
const currentYear = currentDate.getFullYear();
const currentMonth = currentDate.getMonth();
createCalendar(currentYear, currentMonth);
</script>
</html>
실행
마무리
웹개발에 html을 계속 사용해야하기 때문에 오랜만에 재활용 해봤습니다.
뭐든 한번 배운것은 여러번 활용하여 몸에 익혀야 오래 남는 것 같습니다.
반응형