자바스크립트 html 시계

자바스크립트 html시계.

안녕하세요.

오늘은 제가 평소에 쓰던 웹시계의 광고와 디자인이 마음에 들지 않아서 제가 만들어 봤습니다.

html+자바스크립트+css로 만들었으며 조금 허접합니다.

  • 전체 코드
  • 시간 나타내기.
  • 시간 갱신.

전체 코드(미완성입니다.)

코드는 아래와 같습니다.

코드 파일은 깃허브에서 다운받으실 수 있습니다.

(귀찮아서 나중에 링크 올릴게요.) 

더보기

1. index.html

<!DOCTYPE html>
<html lang="kr" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>시계</title>
    <link rel="stylesheet" href="clock.css" />
    <style media="screen">
      .buttonlist{
        margin-top:2%;
        text-align: center;
      }
      input[type="text"],
      input[type="password"],
      input[type="email"],
      select,
      textarea {
        background: rgba(144, 144, 144, 0.075);
        border-color: rgba(144, 144, 144, 0.25);
      }
    </style>
  </head>

  <body style="background: black">
      <!-- Header -->
        <header id="header">
          <div class="logo"><a href="index.html">clock project - <span>yunminseong</span></a></div>
        </header>
      <div class="showtime">
        <h1 class='text'>현재시간</h1>
        <div class="with">
          <h1 id="clock0" >오전오후</h1>
          <h1 id="clock1" >00:00</h1>
        </div>
        <p id="clock2" >년,월,일,요일</p>
      </div>
      <div class="buttonlist">
        <button type="button" class="snip1535"onclick="toggleModal();">List</button>
        <button type="button" class="snip1535"onclick="ssstime();">시간저장</button>
        <button type="button" class="snip1535"onclick="sfullsize();">fullsize</button>
      </div>
      <div class="showtimes">
        <div class="modal-content">
            <span class="close-button" onClick='toggleModal()'>&times;</span>
            <form action="./change.php" method="post" style="width:100%;height:90%;">
              <input type="password" name="cpw" placeholder="바꿀 비밀번호" value="">
              <button type="button" class="snip1535"onclick="ssstime();">시간저장</button>
              <h1 id="clock3" >저장된시간</h1>
            </form>
        </div>
      </div>
    <!-- Footer -->
      <footer id="footer">
        <div class="inner">
          <h2>Credit by</h2>
          <form action="#" method="post">
            <div class="field half first">
              <label for="name">Development time = 19.12.21 ~ 19.12.22</label>
            </div>
            <div class="field half">
              <label for="email">Development staff = yunminseong</label>
            </div>
        </div>
      </footer>

    <script src="clock.js"></script>
    <script type="text/javascript">

    </script>

  </body>
</html>

2. clock.css

body{
  width: 99%;
  height: 99%;
}
.showtime{
  padding-top:12%;
  width:100%;
  height: 100%;
  color:gray;
  text-align: center;
}
.text{
  font-size: 100%;
}
#clock0{
  font-size: 170%;
  display: inline-block;
}
#clock1{
  font-size: 400%;
  display: inline-block;
}
#clock2{
  font-size: 150%;
}
#clock3{
  font-size: 150%;
  color:gray;
}
.with{
  margin-top:-30px;
  margin-bottom:-30px;
}
/* Header */
		#header .logo {
			display: inline-block;
			height: inherit;
			left: 1.5em;
			line-height: inherit;
			margin: 0;
			padding: 10px;
			position: absolute;
			top: 0;
		}
			#header .logo a {
				font-size: 1.25em;
				color: #fff;
				font-weight: 600;
				text-decoration: none;
			}

				#header .logo a:hover {
					color: #fff;
				}

			#header .logo span {
				font-weight: 300;
				font-size: .8em;
				color: #FFF;
			}
/**/
#cancel {
    width: 127px; height: 48px;
    text-align: center;
    border: none;
    margin-top: 20px;
    cursor: pointer;
}
#cancel:hover{
    color: #fff;
    background-color: #216282;
    opacity: 0.9;
}
.showtimes {
      position: fixed;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      /*background-color: rgba(0, 0, 0, 0.5);*/
      opacity: 0;
      visibility: hidden;
      transform: scale(1.0);
      transition: visibility 0s linear 0.25s, opacity 0.25s 0s, transform 0.25s;
  }
.modal-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #222222;
    padding: 1rem 1.5rem;
    width: 500px;
    height: 350px;
    border-radius: 0.5rem;
}
.close-button {
    float: right;
    width: 1.5rem;
    line-height: 1.5rem;
    text-align: center;
    cursor: pointer;
    border-radius: 0.25rem;
    background-color: lightgray;
}
.close-button:hover {
    background-color: darkgray;
}
.show-showtimes {
   opacity: 1;
   visibility: visible;
   transform: scale(1.0);
   transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;
}

/*버튼*/
.snip1535 {
/*background-color: #c47135;*/
background-color: #444444;
border: none;
color: #ffffff;
cursor: pointer;
display: inline-block;
font-family: 'BenchNine', Arial, sans-serif;
font-size: 1em;
font-size: 80%;
line-height: 1em;
margin: 15px 40px;
outline: none;
padding: 12px 40px 10px;
position: relative;
text-transform: uppercase;
font-weight: 700;
}
.snip1535:before,
.snip1535:after {
border-color: transparent;
-webkit-transition: all 0.25s;
transition: all 0.25s;
border-style: solid;
border-width: 0;
content: "";
height: 24px;
position: absolute;
width: 24px;
}
.snip1535:before {
border-color: #c47135;
border-right-width: 2px;
border-top-width: 2px;
right: -5px;
top: -5px;
}
.snip1535:after {
border-bottom-width: 2px;
border-color: #c47135;
border-left-width: 2px;
bottom: -5px;
left: -5px;
}
.snip1535:hover,
.snip1535.hover {
background-color: #c47135;
}
.snip1535:hover:before,
.snip1535.hover:before,
.snip1535:hover:after,
.snip1535.hover:after {
height: 100%;
width: 100%;
}
/* Footer */

#footer {
	color: gray;
	padding-top: 20%;
    padding-bottom: 10%;
	background: black;
    text-align: center;
}

3. clock.js

var clockTarget0 = document.getElementById("clock0");
var clockTarget1 = document.getElementById("clock1");
var clockTarget2 = document.getElementById("clock2");
var clockTarget3 = document.getElementById("clock3");

function clock() {
  var ampm='오전'; //오전 오후 초기값
  var date = new Date();
  var year = date.getFullYear();
  var month = date.getMonth();
  var clockDate = date.getDate();
  var day = date.getDay();
  var week = ['일', '월', '화', '수', '목', '금', '토'];
  var hours =addZeros(date.getHours(),2);
  var minutes =addZeros(date.getMinutes(),2);
  var seconds =addZeros(date.getSeconds(),2);
  //clockTarget1.innerText =  `${hours < 10 ? `0${hours}` : hours}:${minutes < 10 ? `0${minutes }`  : minutes }:${seconds < 10 ? `0${seconds }`  : seconds }`;
  if(hours>=12){
    ampm='오후';
    if(hours>12)
    hours=addZeros(hours - 12,2);
  }
  clockTarget0.innerText = `${ampm}`;
  clockTarget1.innerText = `${hours}:${minutes}:${seconds}`;
  clockTarget2.innerText = `${year}년 ${month+1}월 ${clockDate}일 ${week[day]}요일` ;

}
function ssstime(){
  var ampm='오전'; //오전 오후 초기값
  var date = new Date();
  var year = date.getFullYear();
  var month = date.getMonth();
  var clockDate = date.getDate();
  var day = date.getDay();
  var week = ['일', '월', '화', '수', '목', '금', '토'];
  var hours =addZeros(date.getHours(),2);
  var minutes =addZeros(date.getMinutes(),2);
  var seconds =addZeros(date.getSeconds(),2);
  //clockTarget1.innerText =  `${hours < 10 ? `0${hours}` : hours}:${minutes < 10 ? `0${minutes }`  : minutes }:${seconds < 10 ? `0${seconds }`  : seconds }`;
  if(hours>=12){
    ampm='오후';
    if(hours>12)
    hours=addZeros(hours - 12,2);
  }

  clockTarget3.innerText=`${ampm}\n${hours}:${minutes}:${seconds}\n${year}년 ${month+1}월 ${clockDate}일 ${week[day]}요일`;
}
function sfullsize(){
  document.documentElement.webkitRequestFullscreen();
}
function init() {
  clock();
  setInterval(clock, 1000);
}
function addZeros(num, digit) { // 자릿수 맞춰주기
   var zero = '';
   num = num.toString();
   if (num.length < digit) {
      for (i = 0; i < digit - num.length; i++) {
         zero += '0';
      }
   }
   return zero + num;
}
init();

//보였다 안보였다
var showtimes = document.querySelector(".showtimes");
function toggleModal() {
     showtimes.classList.toggle("show-showtimes");
 }
 /*버튼*/
 $(".hover").mouseleave(
 function() {
   $(this).removeClass("hover");
 }
 );

 

시간 나타내기

모든 코드에 대한 설명은 하지 않겠습니다.

시간을 나타내는 부분의 설명만 하겠습니다.

1. 자바스크립트 clock()함수

num 변수 사용한 함수 간단한 설명
1. ampm 없음 초기값은 오전으로 나중에 계산해서 출력됨.
2. date new Date() 현재 시간데이터를 가져옴.
3. year date.getFullYear() 년도에 대한 데이터를 year변수에 저장.
4. month date.getMonth() 월에 대한 데이터를 month변수에 저장.
5. clockDate date.getDate() 일에 대한 데이터를 clockDate변수에 저장.
6. day date.getDay() 요일에 대한 데이터를 정수형으로 day변수에 저장
7. week 배열 요일을 배열에 선언.
8. hours date.getHours() date에 저장된 시간을 변수hours에 저장 
9. minutes date.getMinutes() date에 저장된 분을 변수minutes에 저장 
10. seconds date.getSeconds() date에 저장된 초을 변수seconds에 저장 

이 함수만 있다면 이렇게 시간을 표시할 수 있습니다.

물론 css가 없으므로 이쁘지는 않을겁니다.

(자바스크립트로 다른 html태그에 써주는 부분이 있는데 그 부분은 위의 clock함수의 innerText부분을 참고하세요.)

일단 이 함수만 있어도 시계가 어찌어찌 작동은 할겁니다.

시간 갱신

문제는 저 코드만 있으면 clock()함수를 불러왔을때의 시간만 나타낼 것이라는 점입니다.

즉, 시계가 움직이지 않을겁니다.

그러니 시간을 1초마다 다시 표시할 수 있도록 만들어주겠습니다.

function init()이라는 이름의 함수를 하나 만들어주었습니다.

그 후 clock()을 한번 실행하고 setInterval이라는 함수를 통해 clock함수를 1초에 한번씩 실행시켜줍니다.

function init() {
  clock();
  setInterval(clock, 1000);
}
init();

이렇게 하면 1초에 한번씩 clock함수를 실행하며 바뀐 시간을 계속해서 화면에 갱신해줄겁니다.

추가

흠.. 조금 틀린부분이 많이 있을 수 있으며 자바스크립트를 몇 번 만져보지 못해서 미숙한부분이 많습니다.

버튼 디자인은 https://nanati.me/css-button-design/ <--이분 블로그에서 가져왔습니다.

https://ykarr.github.io/web/

 

시계

 

ykarr.github.io

Designed by JB FACTORY