[Vanilla JS] : 시계/현재시간 노출
5673 단어 vanilla jsJavaScriptJavaScript
🍧 1. 설명
[기능]
단순히 현재 시간이 노출되도록 구현했다.
- Date함수를 사용하여 시간을 노출하고, setInterval을 사용하여 1초마다 시간을 가져오는 getClock함수를 호출하여 현재 시간에 해당하는 값이 1초단위로 변경하도록 한다.
- innerText로 HTML에 변경된 값을 넣어준다.
- 시간 값을 가져오면 삼항연산자를 사용하여 한자리 수일 때는 0을 붙여준다. (예 : 0:30:59 -> 00:30:59)
[구현화면]
🍦 2. 코드
[index.html]
<!DOCTYPE html>
<head>
<title>바닐라 시계</title>
<style type="text/css">@import url("watch.css");</style>
</head>
<body>
<div>
<p>바닐라 시계</p>
<div class="display_time">
<!--시간 노출-->
<span id="clock">00</span>
</div>
</body>
<script src="watch.js"></script>
</html>
[watch.css]
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+KR&display=swap');
body {
text-align: center;
font-family: 'Noto Sans KR', sans-serif;
font-size: large;
color: wheat;
background-color:lightslategrey;
}
p {
font-size: 100px;
margin-bottom: 10px;
}
.display_time {
font-size: 120px;
}
[watch.js]
function getClock() {
const date = new Date();
const hour = date.getHours();
const min = date.getMinutes();
const sec = date.getSeconds();
console.log(hour);
const clock = document.getElementById("clock");
clock.innerText = `${hour < 10 ? `0${hour}`:hour}:${min < 10 ? `0${min}`:min}:${sec < 10 ? `0${sec}`:sec}`;
}
function init() {
getClock();
setInterval(getClock, 1000); //1초
}
init();
Author And Source
이 문제에 관하여([Vanilla JS] : 시계/현재시간 노출), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@aram/Vanilla-JS-시계현재시간-노출저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)