다재다능한 모험가
Js 달력만들기 본문
제이쿼리를 이용해 css를 꾸며주었음
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="date.css" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
</head>
</head>
<body>
<div class="container">
<input type="text" id="input_date">
<div id="div_calendar">
<div>
<button type="button" onclick="changeMonth(-1)"><i class="fa fa-chevron-left"></i></button>
<input type="number" id="year" value="2020" style="width: 80;display: initail" class="form-contorl">
<select id="month" class="form-contorl" style="width: 80;display: initail" onchange="changeMonth()">
<option value="1">1월</option>
<option value="2">2월</option>
<option value="3">3월</option>
<option value="4">4월</option>
<option value="6">6월</option>
<option value="5">5월</option>
<option value="7">7월</option>
<option value="8">8월</option>
<option value="9">9월</option>
<option value="10">10월</option>
<option value="11">11월</option>
<option value="12">12월</option></select>
<button type="button" onclick="changeMonth(1)"><i class="fa fa-chevron-right"></i></button>
</div>
<table class="table table-bordered">
<thead>
<th>일</th>
<th>월</th>
<th>화</th>
<th>수</th>
<th>목</th>
<th>금</th>
<th>토</th>
</thead>
<tbody id="tb_body"></tbody>
</table>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
<script src="index.js"></script>
</body>
</html>
HTML태그는
table태그를 이용해 달력을 만들었고
select-option을 이용해 월을 선택할 수 있게 만들었음
thead태그에는 월화수목금토일을 만들어주었고
달력의 날짜들이 들어갈 tbody를 만들어줌
년도를 보여줄 input과
월을 이동할 수 있는 버튼 태그를 두개 만들어줌
전달로 이동하는 버튼
다음달로 이동하는 버튼
JavaScript 코드
function checkLeapYear(year) {
//윤년계산
if (year % 400 == 0) {
return true;
} else if (year % 100 == 0) {
return false;
} else if (year % 4 == 0) {
return true;
} else {
return false;
}
}
function getFirstDayOfWeek(year, month) {
if (month < 10) month = "0" + month;
return new Date(year + "-" + month + "-01").getDay();
}
function changeYearMonth(year, month) {
let month_day = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (month == 2) {
if (checkLeapYear(year)) month_day[1] = 29;
}
let first_day_of_week = getFirstDayOfWeek(year, month);
let arr_calendar = [];
for (let i = 0; i < first_day_of_week; i++) {
arr_calendar.push("");
}
for (let i = 1; i <= month_day[month - 1]; i++) {
arr_calendar.push(String(i));
}
let remain_day = 7 - (arr_calendar.length % 7);
if (remain_day < 7) {
for (let i = 0; i < remain_day; i++) {
arr_calendar.push("");
}
}
renderCalendar(arr_calendar);
}
function renderCalendar(data) {
let h = [];
for (let i = 0; i < data.length; i++) {
if (i == 0) {
h.push("<tr>");
} else if (i % 7 == 0) {
h.push("</tr>");
h.push("<tr>");
}
h.push(
'<td onclick="setDate(' +
data[i] +
');" style="cursor:pointer">' +
data[i] +
"</td>"
);
}
h.push("</tr>");
$("#tb_body").html(h.join("")); //$() 이형태는 J쿼리에서만 가능
}
function setDate(day) {
if (day < 10) day = "0" + day;
$("#input_date").val(current_year + "-" + current_month + "-" + day);
$("#div_calendar").hide();
}
function changeMonth(diff) {
if (diff == undefined) {
//select 박스에서 선택 했을 때
current_month = parseInt($("#month").val());
} else {
current_month = current_month + diff;
if (current_month == 0) {
current_year = current_year - 1;
current_month = 12;
} else if (current_month == 13) {
current_year = current_year + 1;
current_month = 1;
}
}
loadCalendar();
}
function loadCalendar() {
$("#year").val(current_year);
$("#month").val(current_month);
changeYearMonth(current_year, current_month);
}
let current_year = new Date().getFullYear(); //년도를 가져옴
let current_month = new Date().getMonth() + 1; //getMonth를 해주면 1월이 0으로 오기 떄문에 +1을 해줌
$("#year").val(current_year);
$("#month").val(current_month);
changeYearMonth(2020, 12);
$("#input_date").click(function () {
$("#div_calendar").toggle();
});
먼저 윤년 계산하는 함수를 만들어줌
년도를 파라미터로 받고
년도가 400으로 떨어지면 true를 100으로 떨어지면 false 4로 떨어지면 true
이런식으로 윤년을 확인하는 조건문을 만들어줌
getFirstDayOfWeek라는 함수를 만들어주고 year, month를 파라미터로 받음
조건문으로 10월 미만의 월에는 앞에 0을 붙어줌
new Date로 날짜를 생성하는데
해당년월의 1일의 요일이 몇요일인지 getDay를 통해 가져옴
getFirstDayWeek함수는 해당년월에 첫번째 날짜가 몇요일인지를 리턴함
changeYearMonth 함수를 만들어줌
조건문을 이용해
2월달이 윤년이묜 month_day의 인덱스 1을 =29일로 바꿔줌
fist_day_of_week에 getFirstDayofWeek를 넣어줌(1일의 요일)
arr_calendar를 빈배열로 선언함
반복문을 이용해 i가 first_day_of_week보다 작으면 빈배열을 추가함
그리고 다시 반복문을 이용해 Month_day만큼 날짜들을 추가해줌(index는 0부터 시작하기 때문에 month_day[month-1]을 해줌)
let remain_day = 7 - (arr_calendar.length % 7);
리마인드 데이에 7- (남은일수 %7)을 넣어줌
리마인드데이가 7보다 작은경우 리마인드데이만큼 빈배열을 추가해줌
그리고 rederCalenar함수의 파라미터로 arr_calendar를 넣어줌
renderCalendar()함수는 html코드로 출력해주는 함수임
h를 빈배열로 선언해주고
파라미터로 받은 배열의 길이만큼
h배열에 <tr>태그를 추가해주고 배열이 7일이 될때마다 tr태그를 닫고 열어줌
html 테이블에 각 data[i]로 가져온 날짜 데이터로 셀을 생성하고 클릭했을 때 setDate() 함수를 호출함
그리고 </tr>태그로 닫아줘
$("#tb_body").html(h.join("")); //$() 이형태는 J쿼리에서만 가능
id가 tb_body인 html코드에 h배열을 join으로 결합해줌
j쿼리를 사용하지 않고 만든다면
쿼리셀렉트를 이용해 결합해줄 수도 있음
diff에 매개변수가 없으면 (undefined)
선택된 select요소에서 월 값을 가져와서 현재 월로 설정함
else 그렇지 않으면 현재월을 증가시킴
current_month가 0이면
전년도로 바꾸고 12월로 바꿔줌
else if 13월이면 다음년도로 바꾸고 월을 1월로 바꿈
loadClalendar를 호출해 새로운 월에 해당하는 달력을 출력함
setDate함수는
조건문을 이용해 일수가 10일 미만이면 앞에 0을 붙여줌
input_date의 value를 current ( current_year + "-" + current_month + "-" + day)로 변경
hide()함수를 이용해 달력을 숨김
loadCalendar() 함수는 현재 년도와 월을 설정하고 changeYearMonth 함수를 호출해 해당 년도와 월에 대한 달력을 로드하는 함수임
current_year, month변수는 년도와 월을 가져오는데 사용
그리고 아래 값은 id year,month의 value값으로 current_year과 current_month를 넘겨줌
그리고 j쿼리 문법을 사용하지 않고 작성하면
쿼리 셀렉터로 접근할 수 있음
'Js' 카테고리의 다른 글
모던자바스크립트(2) (0) | 2024.03.29 |
---|---|
모던자바스크립트(1) (0) | 2024.03.28 |
JavaScript 인터랙티브 자바스크립트(3) (0) | 2024.03.24 |
JavaScript 인터랙티브 자바스크립트(2) (1) | 2024.03.23 |
인터랙티브 자바스크립트(1) (1) | 2024.03.22 |