실시간 현재 시간을 알려줍니다.
<html lang="ko"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css" /> <title>Clock</title> </head> <body> <main class="container"> <h1 id="title">00:00</h1> </main> <script src="clock.js"></script> </body> </html>
main {
width: 100%;
height: 100vh;
background-color: gainsboro;
display: flex;
justify-content: center;
align-items: center;
}
#title {
font-size: 180px;
}
var clockContainer = document.querySelector('main');
var clockTitle = clockContainer.querySelector('#title');
function getTime() {
var date = new Date(); // Date class
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
if (seconds > 50) {
clockTitle.style.color = 'red';
} else {
clockTitle.style.color = 'black';
}
clockTitle.innerText = `${hours < 10 ? `0${hours}` : hours}:${minutes < 10 ? `0${minutes}` : minutes}:${seconds < 10 ? `0${seconds}` :seconds}`;
}
function init() {
getTime();
setInterval(getTime, 1000);
}
init();