본문 바로가기

WINK-(Web & App)/HTML & CSS & JS 스터디

[2023 신입부원 심화 스터디] 신진욱 #4주차 - Part 6

반응형

그동안 강의를 통해 배운 js를 이용하여 예제 만들기 실습

<예제>

1. 모달 만들기

- 모달 만들기는 👉 Click 버튼을 누르면 모달 내용만 보이고 Close 버튼을 누르면 👉 Click 버튼만 보이게 하기

  • index.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" />
    <link rel="stylesheet" href="style.css" />
    <title>Document</title>
  </head>
  <body>
    <button class="open">👉 Click</button>

    <div class="container">
      <div class="modal">
        <h2>Lorem, ipsum dolor.</h2>
        <p>
          Lorem, ipsum dolor sit amet consectetur adipisicing elit. Reiciendis,
          excepturi?
        </p>
        <button class="close">Close</button>
      </div>
    </div>

    <script src="./index.js"></script>
  </body>
</html>
  • style.css

- 기본 container class의 display는 none 속성이기에 모달 내용이 첫 화면에 보이지 않는다.

...

.container {
    position: absolute;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    display: none;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  
  ...
  • index.js

- 이벤트 리스너를 등록 후 요소의 속성 변경 기능을 구현

- 버튼에 addEventListener를 등록 후 click 이벤트가 발생하면 container와 open 클래스의 display 속성 값을 반대로 지정

const openButton = document.querySelector('.open'); 
const container = document.querySelector('.container');
const closeButton = document.querySelector('.close');

openButton.addEventListener('click', () => {
    container.style.display = "flex"; // click버튼을 누르면 modal창을 화면에 보이게 한다.
    openButton.style.display = "none"; // modal창이 나오면 open버튼은 화면에서 사라지게 한다.
});

closeButton.addEventListener('click', () => {
    container.style.display = "none"; // close 버튼을 누르면 modal창은 화면에서 사라지게 한다.
    openButton.style.display = "flex"; // close 버튼을 누르면 click버튼을 화면에 보이게 한다.
});

 

2. 할 일 앱 만들기

- 할 일 앱 만들기는 입력란에 글을 입력하고 엔터 or 등록 버튼을 눌렀을 때 입력 내용들을 모두 웹 화면에 보이게 하기

  • index.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" />
    <link rel="stylesheet" href="style.css" />
    <title>Document</title>
  </head>
  <body>
    <form>
      <input type="text" placeholder="할 일을 입력하세요." />
      <button>등록</button>
    </form> 

    <ul></ul>

    <script src="./index.js"></script>
  </body>
</html>

 

  • index.js

- 할 일 추가하기 기능 구현 (삭제 기능 X, 리스트 저장 기능 X)

const form = document.querySelector('form');
const input = document.querySelector('input');
const ul = document.querySelector('ul');

form.addEventListener('submit', (event) => {
    event.preventDefault(); // event 객체가 가지고있는 preventDefault() 메소드 사용
    // 입력값을 제출할때 새로고침이 되어서 사용자가 입력한 값이 사용되지 않는 문제를 해결
    
    if (input.value !== '') { // 사용자가 아무것도 입력하지 않고 제출했을 때 경우 고려하기
        const li = document.createElement('li'); // 리스트 생성
        li.innerText = input.value; // 리스트에 입력값 넣기
        ul.appendChild(li); // 리스트를 ul에 넣기 -> 화면에 li 내용들이 보인다.
        input.value = ''; // 입력후 제출하고나서 입력란에 사용한 값이 남아있지 않게 하기
    }
});

 

3.디지털 시계 만들기

- 디지털 시계만들기는 time hour , time min , time sec  클래스의 00 텍스트를 현재 시간으로 바꿔주기

<!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" />
    <link rel="stylesheet" href="style.css" />
    <title>Document</title>
  </head>
  <body>
    <div class="time hour">00</div>
    <div class="divider">:</div>
    <div class="time min">00</div>
    <div class="divider">:</div>
    <div class="time sec">00</div>

    <script src="./index.js"></script>
  </body>
</html>
  • index.js

- 현재 시간을 가져와 hour, min, sec 클래스의 텍스트 변경 기능 구현

 

const hour = document.querySelector('.hour');
const min = document.querySelector('.min');
const sec = document.querySelector('.sec');

function clock() {
    const now = new Date(); // Date 객체 생성해서 이 객체가 가지고 있는 메소드를 사용하여 현재 시,분,초 가져오기

    hour.innerText = now.getHours();
    min.innerText = now.getMinutes();
    sec.innerText = now.getSeconds();
}
// 위에 3개만 작성하면 시간을 가져오긴하지만 딱 한번만 가져옴.

setInterval(clock, 1000) 
// 일정한 시간마다 동일한 작업을 수행하기 위함. setInterval(a,b) : a = 반복해서 실행할 함수 b = delay 시간
// 1초마다 실행하기 (밀리세컨즈)

 

4. 가위바위보 게임 만들기

- 사용자가 가위, 바위, 보 중 하나를 선택하면 컴퓨터는 랜덤으로 하나를 선택하고 서로 비교하여 승패를 정하기

  • index.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" />
    <link rel="stylesheet" href="style.css" />
    <title>Document</title>
  </head>
  <body>
    <div class="container">
      <div class="block">
        <h3>컴퓨터 선택 :</h3>
        <p class="computer-choice">??</p>
      </div>
      <div class="block">
        <h3>당신 선택 :</h3>
        <p class="you-choice">??</p>
      </div>
    </div>

    <div class="buttons">
      <button class="red">가위</button>
      <button class="blue">바위</button>
      <button class="green">보</button>
    </div>

    <div class="result">가위바위보!</div>

    <script src="./index.js"></script>
  </body>
</html>
  • index.js

- 가위, 바위, 보 중에서 사용자가 선택한 것, 컴퓨터에 랜덤으로 하나 선택한 것, 게임 결과를 보여주는 기능 구현

const buttons = document.querySelectorAll('button'); // 가위, 바위, 보 3개의 버튼을 리스트 형태로 buttons로 받기
const computerChoice = document.querySelector('.computer-choice');
const userChoice = document.querySelector('.you-choice');
const winner = document.querySelector('.result');

// 컴퓨터에 랜덤으로 세 값중 하나 지정하기 : 배열 생성 후 인덱스 값을 랜덤으로 받아서 값 지정
const result = ['가위', '바위', '보'];

// 사용자에게 클릭한 버튼 값 할당, 컴퓨터에게 랜덤 값 할당
const play = (event) => {
    const user = event.target.innerText;
    const randomIndex = Math.floor(Math.random() * 3); // 0~2 중 하나의 난수 생성
    // Math.random(); // 0~1사이에 있는 부동소수점 난수 생성
    const computer = result[randomIndex];
    game(user, computer);
};

// 가위, 바위, 보 세 버튼중 하나 클릭 하면 랜덤으로 세 버튼 중 하나의 값을 컴퓨터에 전달
buttons.forEach((button) => {
    button.addEventListener('click', play)
});

// 사용자, 컴퓨터가 낸 것과 게임 결과 보여주기
const show = (user, computer, result) => {
    computerChoice.innerText = computer;
    userChoice.innerText = user;
    winner.innerText = result;
}

// 승,무,패 정하기
const game = (user, computer) => {
    let message;
    if (user === computer) {
        message = '무승부';
    } else {
        switch (user + computer) { // 더하기 연산은 숫자끼리 하면 숫자의 덧셈, 텍스트 값이 하나라도 있으면 두 피연산자를 붙인 텍스트를 만든다.
            // 가위보, 바위가위, 보바위 -> 유저 승
            case '가위보':
            case '바위가위':
            case '보바위':
                message = '사용자 승리!';
                break;
            // 가위바위, 바위보, 보가위 -> 컴퓨터 승
            case '가위바위':
            case '바위보':
            case '보가위':
                message = '컴퓨터 승리!';
                break;
        }
    }
    show(user, computer, message);
};

 

5. 업그레이드 된 할 일 앱 만들기

- 2번 실습에서 더 나아가 할 일들을 삭제도 해주고 웹페이지를 초기화 해도 이전 값들을 받아와서 화면에 보여주기

  • index.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" />
    <link rel="stylesheet" href="style.css" />
    <title>Document</title>
  </head>
  <body>
    <form>
      <input type="text" placeholder="할 일을 입력하세요." />
      <button>등록</button>
    </form>

    <ul></ul>

    <script src="./index.js"></script>
  </body>
</html>
  • index.js

- 1. 삭제 기능 구현 및 버튼을 추가

- 2. 저장 하기 >> web storage 사용

- 3. 삭제 버튼 >> 저장된 데이터 업데이트

const form = document.querySelector('form');
const input = document.querySelector('input');
const ul = document.querySelector('ul');

let todos = [];

// 현재 화면에 있는 값들을 저장
const save = () => {
    localStorage.setItem('todos', JSON.stringify(todos)); // 변화된 todos 값을 문자열로 변환하여 이전 todos에 초기화해주기
};

// 값 삭제 기능
const delItem = (event) => {
    const target = event.target.parentElement;
    
    todos.filter((todo) => todo.id != target.id); // 지우려는 타겟의 값과 같지 않은 원소들만 모아서 다시 만들기 
    // todo.id !== target.id 이렇게 하면 target.id가 문자열이라 원하는 대로 되지 않는다. 
    // 해결책 : 1. != 내용물만 비교 2. todo.id !== parseInt(target.id)
    
    save();
    target.remove(); // 삭제 버튼 누른 것만 사라짐
};

// 값 추가 기능
const additem = (todo) => {
    if (todo.text !== '') {
        const li = document.createElement('li');
        const button = document.createElement('button');
        const span = document.createElement('span'); // span 태그를 이용하여 입력 값과 삭제 버튼을 함께 li 태그로 보내주기

        span.innerText = todo.text;
        button.innerText = '삭제';
        button.addEventListener('click', delItem);
        
        li.appendChild(span);
        li.appendChild(button);
        ul.appendChild(li);
        li.id = todo.id; // li id와 todo id 같게 하기 -> 삭제 원소 구분 목적
      }
};

// 제출 누르면 입력 값들 화면에 추가하기
const handler = (event) => {
    event.preventDefault(); // 제출할때 새로고침 방지
	
    const todo = {
        id: Date.now(),
        text: input.value,
    }; 

    todos.push(todo); // 배열에 집합 형태의 원소를 담기
    additem(todo);
    save();
    input.value = '';
};

// 창을 껐다 키거나 새로고침 했을때 로컬 스토리지에 정보가 있다면 해당 정보를 알아서 생성하게 하기 (이벤트 발생과는 무관)
const init = () => {
    const userTodos = JSON.parse(localStorage.getItem('todos')); // 자바 스크립트 형태로 파싱 해주기
    // todos에 값이 있었다면 userTodos로 값 복사해주기
    if (userTodos) {
        userTodos.forEach((todo) => {
            additem(todo);
        });
        todos = userTodos;
    }
};

init();
form.addEventListener('submit', handler);

 

 

반응형