Web/jQuery
jQuery - 일정 시간이 지나면 css 변환
leebean
2022. 4. 7. 13:19
개인 프로젝트를 진행 하던 중 12시가 지나면 메인 화면이 변하는 기능이 있으면 어떨까 라고 생각하여 만들게 되었습니다. 하지만 만들고 보니 화면 뿐만 아니라 다른 부분도 시간이 지나면 다르게 할 수 도 있겠다는 생각을 했습니다.
github : https://github.com/delight-HK3/Time_change
GitHub - delight-HK3/Time_change: After 12 o'clock the css class changes.
After 12 o'clock the css class changes. Contribute to delight-HK3/Time_change development by creating an account on GitHub.
github.com
(jQuery파일도 함께 첨부했습니다.)
HTML
<html>
<head>
<!-- time_change의 css-->
<link rel="stylesheet" href="/css/time_change.css">
</head>
<body>
<p id="hello">12시가 지나면 색이 바뀝니다 background 색이 바뀝니다.</p>
</body>
</html>
<!-- time_change의 jquery-->
<script src="/js/jquery-3.6.0.js"></script>
<script src="/js/time_change.js"></script>
CSS
.morning {
background: red;
/*12시가 안지나면 id가 hello인 태그는 백그라운드가 red로 바뀜*/
color: white;
padding: 10px;
}
.dinner {
background: blue;
/*12시가 지나면 id가 hello인 태그는 백그라운드가 blue로 바뀜*/
color: white;
padding: 10px;
}
jQuery
$(document).ready(function(){// 페이지가 시작하면 바로적용
let date1 = new Date(); // 현재 년,월,일,시간을 저장
let year = date1.getFullYear(); // 현재 년도를 year에 저장
let hours = 12; // 12시 고정으로 hours 저장
let month = date1.getMonth(); // 현재 월을 month에 저장
let date = date1.getDate(); // 현재 일을 date에 저장
let date2 = new Date(year,month,date,hours);
// 12시는 고정으로 나머지, 년도,월,일은 현재 시
if(date1 < date2){ // 12시 이전인 경우
$('#hello').addClass("morning"); // 12시 이전이면 morning class 추가
$('#hello').removeClass("dinner"); // 12시가 이전이면 dinner class 제거
}
else{// 12시가 지난 경우
$('#hello').addClass("dinner"); // 12시가 지나면 dinner class 추가
$('#hello').removeClass("morning"); // 12시가 지나면 morning class 제거
}
});