본문 바로가기
개발공부/JavaScript

[바닐라 js로 크롬 앱만들기] 인강정리 (#5, #6)

by dokii 2022. 3. 26.
728x90

목차

  1. 시계만들기 (일정간격으로 동작하도록하는 interval)
  2. 시계만들기 (자릿수를 채워주는 padStart())
  3. 랜덤텍스트 (1이하의 랜덤한 소수를 만들어주는 Math.random())
  4. 랜덤이미지 (html에서 요소를 새롭게 생성하는 createElement())

1. interval :매번 일어나야하는 무언가. (ex. 2초마다), 

html


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>replit</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
	  <form id="login-form" class="hidden">
    </form>
    <h1 class="hidden" id="greeting"></h1>
    <h2 id="clock">00:00</h2>
    <script src="greetings.js"></script>
    <script src="clock.js"></script>
  </body>
</html>

clock.js

const clock=document.querySelector("h2#clock");

function getClock() {
  const date = new Date();
  //console.log(`${date.getHours()}:${date.getMinutes}:${date.getSeconds`)
clock.innerText = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
  
}

//setInterval(getClock,1000)//(실행시킬대상, 호출시킬밀리초)
//setTimeout(sayHello,5000)//(실행시킬대상, 호출시킬밀리미터초)

getClock();
setInterval(getClock,1000);

 

2. 초단위 자릿수를 두자리로 표현되도록 만들어보자. (padStart())

-"String".padStart(3,"0") : String을 검사해서, 자릿수가 3이안된다면 앞자리부터 padding을 추가해주세요. 이때 공백은 0으로 채워주세요.

-String타입으로 바꾸려면 String()으로 감싸주면 됨.

clock.js

const clock=document.querySelector("h2#clock");

function getClock() {
  const date = new Date();
  const hours = String(date.getHours()).padStart(2,"0");
  const minutes = String(date.getMinutes()).padStart(2,"0");
  const seconds = String(date.getSeconds()).padStart(2,"0");

clock.innerText = `${hours}:${minutes}:${seconds}`;
  
}

//setInterval(getClock,1000)//(실행시킬대상, 호출시킬밀리초)
//setTimeout(sayHello,5000)//(실행시킬대상, 호출시킬밀리미터초)

getClock();
setInterval(getClock,1000);

 

3. Math.random()을 사용하여 배열의 데이터를 랜덤으로 노출시켜 보자.

- Math.random()은 1이하의 소수로 랜덤한 숫자가 나온다. 랜덤하게 배열에서 추출할경우, 해당 배열의 length를 곱해주면 배열길이를 랜덤하게 구할수 있으므로 배열안에있는 값을 랜덤하게 가져오게 사용할수 있다!

- Math.random()*10 은 0~9까지의 랜덤한 정수를

- Math.random()*100 은 0~99까지의 랜덤한 정수를 

- 그리고 뒷자리의 소숫점을 해결하는 함수를사용하면 끝(round반올림, ceil올림, floor내림)

foods.js

const foods= [
  { food : "pizza and beer",
    price : "2만원"},
  { food : "sushi and sake",
    price : "5만원"},
  { food : "fried chicken and somack",
    price : "3만원"},
  { food : "taco and beer",
    price : "3만원"},
  { food : "ramen and sosu",
    price : "1천원"},
  { food : "cheese cake and coffee",
    price : "1만원"}  
]

const food = document.querySelector("#food span:first-child");
const price = document.querySelector("#food span:last-child");

const num = Math.floor(Math.random()*(foods.length));
console.log(num)

const todayFood = foods[num];
food.innerText = todayFood.food;
price.innerText = todayFood.price;

 

4. createElement("img") : 괄호안에는 이미지가 존재하는 경로와 파일이름을 적어주면 html에 해당 요소를 추가해주게된다.

-html에 <img src="파일경로"/>를 직접적어주는것과 같은효과를 내는게 목적이다.

js

const images = ["0.jpg","1.jpg","2.jpg"];
const chsenImage = images[Math.floor(Math.random()*(images.length))];

const bgImage = document.createElement("img"); //img라는 엘리먼트를 생성한다. 								

bgImage.src = `img/${chosenImage}`; //여기서 경로를지정

//html에 <img src="파일경로"/>를 하고자하기때문에 img엘리먼트생성과,
//해당 img엘리먼트틔 src(경로)를 써주고, bgImage를 사용하면 된다.

document.body.appendChild(bgImage.src) //반드시 바디에 넣어주는작업을해야 html에 추가가된다!

728x90

댓글