JAVA_Script

자바스크립트(전자시계만들기)

강준석 2022. 12. 27. 17:23
728x90

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <h1 class="clock"></h1>


 <!-- jQuery -->
 <script src="https://code.jquery.com/jquery-3.6.2.min.js" integrity="sha256-2krYZKh//PcchRtd+H+VyyQoZ/e3EcrkxhM8ycwASPA=" crossorigin="anonymous"></script>
 <!-- JS -->
<script src="script.js"></script>
</body>
</html>

 

js

let clock = document.querySelector('.clock');

function showClock(){
const date = new Date();
// ${여기안에 넣으면 문자열이 아닌 계산식으로 인식시킨다}

let hour = String(date.getHours()).padStart(2,0);
let min = String(date.getMinutes()).padStart(2,0);
let sec = String(date.getSeconds()).padStart(2,0);
//1시 1분1 초를 01시01분01초처럼 1의 자리수일때 앞에 0을 붙이기 위해사용
//.padStart(최대자릿수,빈자리매꾸는값)
//String을 쓴이유 : .padStart는 문자열만 인식가능해서

clock.innerHTML=`${hour} : ${min} : ${sec}`;
//html class명 clock에 함수를 넣는다
}
showClock();
//setInterval(showClock,1000);로 인해 새로고침시 1초뒤에 표시되는걸 바로 먼저 나오게 하게
setInterval(showClock,1000);
//showClock함수 1초마다 실행(현재시간이 1초마다 갱신)

 

 

728x90