개발일기

[JS] 달력 만들기 본문

Project Portfolio

[JS] 달력 만들기

츄98 2023. 5. 26. 04:45

결과물..!!!

 

1. html 파일

<!-- 소비 달력 들어가는 부분 -->
<div class="myconsumestatus">
    <!-- 달력 들어가는 부분 147~172 -->
    <div class="consume-view-top container">
      <div class="consume-calender">
        <div class="calendar-section">
          <table class="Calendar">
            <thead>
              <tr>
                <td id="prevCalendar" style="cursor:pointer;">&#60;</td>
                <td colspan="5">
                  <span id="calYear"></span>년
                  <span id="calMonth"></span>월
                </td>
                <td id="nextCalendar" style="cursor:pointer;">&#62;</td>
              </tr>
              <tr>
                <td>일</td>
                <td>월</td>
                <td>화</td>
                <td>수</td>
                <td>목</td>
                <td>금</td>
                <td>토</td>
              </tr>
            </thead>
            <tbody>
            </tbody>
          </table>
        </div>
     </div>
</div>

 

2. css 파일

td {
    width: 30px;
    height: 30px;
}

.myconsumestatus {
    text-align: left;
    font-size: 30px;
    height: 300px;
}

.consume-view-top {
    display: flex;
    margin-bottom: 50px;
}

.Calendar {
    margin-top: 50px;
    text-align: center;
}

.calendar-section {
    background-color: white;
    margin-left: 10px;
    margin-bottom: 10px;
    width: 500px;
    height: 350px;
    border-radius: 5px;
    box-shadow: 0px 35px 20px -30px rgba(0, 0, 0, 0.3);
    padding: 20px;
}

.Calendar>thead>tr:first-child>td {
    font-family: 'MapoFlowerIsland';
    font-size: 1.1em;
    font-weight: bold;
    padding-bottom: 10px;
    color: rgba(109, 86, 68, 0.822);
}

.Calendar>thead>tr:last-child>td {
    font-family: 'MapoFlowerIsland';
    background-color: rgba(231, 57, 34, 0.322);
    color: rgba(109, 86, 68, 0.822);
}

.Day {
    cursor: pointer;
}

.Day.choiceDay {
    background-color: #3E85EF;
    font-family: 'MapoFlowerIsland';
    color: #fff;
    cursor: pointer;
}

 

 

3. javascript 파일

let nowMonth = new Date(); // 현재 달을 페이지를 로드한 날의 달로 초기화
let today = new Date(); // 페이지를 로드한 날짜를 저장
today.setHours(0, 0, 0, 0); // 비교 편의를 위해 today의 시간을 초기화

// 달력 생성 : 해당 달에 맞춰 테이블을 만들고, 날짜를 채워 넣는다.
function buildCalendar(diffDate = null) {
    // 매개변수가 있으면 nowMonth를 diffDate로 바꿔줌
    if (diffDate !== null) {
        nowMonth = diffDate;
    }
    let count = 1;
    let firstDate = new Date(nowMonth.getFullYear(), nowMonth.getMonth(), 1); // 이번달 1일
    let lastDate = new Date(nowMonth.getFullYear(), nowMonth.getMonth() + 1, 0); // 이번달 마지막날

    let tbody_Calendar = document.querySelector(".Calendar > tbody");
    document.getElementById("calYear").innerText = nowMonth.getFullYear(); // 연도 숫자 갱신
    document.getElementById("calMonth").innerText = leftPad(
        nowMonth.getMonth() + 1
    ); // 월 숫자 갱신

    while (tbody_Calendar.rows.length > 0) {
        // 이전 출력결과가 남아있는 경우 초기화
        tbody_Calendar.deleteRow(tbody_Calendar.rows.length - 1);
    }

    let nowRow = tbody_Calendar.insertRow(); // 첫번째 행 추가

    for (let j = 0; j < firstDate.getDay(); j++) {
        // 이번달 1일의 요일만큼
        let nowColumn = nowRow.insertCell(); // 열 추가
    }

    for (
        let nowDay = firstDate;
        nowDay <= lastDate;
        nowDay.setDate(nowDay.getDate() + 1)
    ) {
        // day는 날짜를 저장하는 변수, 이번달 마지막날까지 증가시키며 반복

        let nowColumn = nowRow.insertCell(); // 새 열을 추가하고
        nowColumn.innerText = leftPad(nowDay.getDate()); // 추가한 열에 날짜 입력

        if (nowDay.getDay() == 0) {
            // 일요일인 경우 글자색 빨강으로
            nowColumn.style.color = "#DC143C";
        }
        if (nowDay.getDay() == 6) {
            // 토요일인 경우 글자색 파랑으로 하고
            nowColumn.style.color = "#0000CD";
            nowRow = tbody_Calendar.insertRow(); // 새로운 행 추가
        }

        nowColumn.className = "Day";
        nowColumn.id = `day${count}`;
        count += 1;

        nowColumn.onclick = function () {
            choiceDate(this);
        };
    }
}

// 날짜 선택
function choiceDate(nowColumn) {
    if (document.getElementsByClassName("choiceDay")[0]) {
        // 기존에 선택한 날짜가 있으면
        document
            .getElementsByClassName("choiceDay")[0]
            .classList.remove("choiceDay"); // 해당 날짜의 "choiceDay" class 제거
    }
    nowColumn.classList.add("choiceDay"); // 선택된 날짜에 "choiceDay" class 추가
}

// 이전달 버튼 클릭
function prevCalendar() {
    nowMonth = new Date(
        nowMonth.getFullYear(),
        nowMonth.getMonth() - 1,
        nowMonth.getDate()
    ); // 현재 달을 1 감소
    buildCalendar(); // 달력 다시 생성
}

// 다음달 버튼 클릭
function nextCalendar() {
    nowMonth = new Date(
        nowMonth.getFullYear(),
        nowMonth.getMonth() + 1,
        nowMonth.getDate()
    ); // 현재 달을 1 증가
    buildCalendar(); // 달력 다시 생성
}

// input값이 한자리 숫자인 경우 앞에 '0' 붙혀주는 함수
function leftPad(value) {
    if (value < 10) {
        value = "0" + value;
        return value;
    }
    return value;
}

 

핵심 아이디어: 날짜를 선택하면 해당 태그의 classname을 변경하기

// 날짜 선택
function choiceDate(nowColumn) {
  if (document.getElementsByClassName("choiceDay")[0]) {                              // 기존에 선택한 날짜가 있으면
    document.getElementsByClassName("choiceDay")[0].classList.remove("choiceDay");  // 해당 날짜의 "choiceDay" class 제거
  }
  nowColumn.classList.add("choiceDay"); // 선택된 날짜에 "choiceDay" class 추가
  Choicelist();
}

 

 

다음 글: Choicelist() 함수에 대해서 설명하도록 하겠습니다~ 

2023.05.29 - [Project Portfolio] - [JS] 달력 날짜 누르면 날짜에 해당하는 저축, 소비, 지출 불러오기

 

[JS] 달력 날짜 누르면 날짜에 해당하는 저축, 소비, 지출 불러오기

- 이전 게시글 2023.05.26 - [Project Portfolio] - [JS] 달력 만들기 [JS] 달력 만들기 1. html 파일 < 년 월 > 일 월 화 수 목 금 토 2. css 파일 td { width: 30px; height: 30px; } .myconsumestatus { text-align: left; font-size: 30px; h

developer908.tistory.com

 

 

참고자료