STUDY 📒/Javascript

[바닐라JS 챌린지] DAY5 과제

South Dev 2024. 2. 23. 19:44

✔ 오늘의 강의

바닐라 JS로 크롭앱 만들기 : From #2.13 to #3.8

 

✔ 목표

해당 완성 화면을 보고 App을 만들어보자

완성 화면

✔ 조건

- if/else 등을 사용

 

TA's 힌트

 

참고 링크

https://developer.mozilla.org/en-US/docs/Web/API/Window

 

Window - Web APIs | MDN

The Window interface represents a window containing a DOM document; the document property points to the DOM document loaded in that window.

developer.mozilla.org

 

✔ 과정

1. body태그 안에 Hello! 텍스트를 추가한다.

// 1. body 안에 'hello' h1태그를 추가한다.
const hello = document.createElement("h1");
document.body.append(hello);
hello.innerText = "Hello!";

- createElement로 h1 태그를 설정한다.

- append() 함수를 이용하여 h1에 innerText로 'Hello!'를 추가한다.

 

2. body의 기본 배경을 purple로 지정, h1 태그 컬러를 #fff로 지정

// 2. body의 기본 배경을 pule로 지정, h1 컬러 #fff로 지정
body.style.backgroundColor = "purple";
hello.style.color = "#fff";

 

3. resize() 라고 함수를 만든다. innerWidth, if else를 이용해 창크기 변화에 따른 body 컬러를 설정해 준다.

function resize() {
  const width = window.innerWidth;
  if (width < 800) {
    document.body.style.backgroundColor = "blue";
  } else if (width >= 800 && width <= 1000) {
    document.body.style.backgroundColor = "purple";
  } else {
    document.body.style.backgroundColor = "yellow";
  }
}

window.addEventListener("resize", resize);

 

결과 JS

const body = document.querySelector("body");

// 1. body 안에 'hello' h1태그를 추가한다.
const hello = document.createElement("h1");
document.body.append(hello);
hello.innerText = "Hello!";

// 2. body의 기본 배경을 pule로 지정, h1 컬러 #fff로 지정
body.style.backgroundColor = "purple";
hello.style.color = "#fff";

// 3. resize() 라고 함수를 만든다. innerWidth, if else를 이용해 창크기 변화에 따른 body 컬러를 설정해 준다.
function resize() {
  const width = window.innerWidth;
  if (width < 400) {
    body.style.backgroundColor = "skyblue";
  } else if (width >= 400 && width <= 600) {
    body.style.backgroundColor = "purple";
  } else {
    body.style.backgroundColor = "orange";
  }
}

window.addEventListener("resize", resize);

 

 

✔ 기억하고 싶은 점

- append()

// append()로 활용할 수 있는 다른 예시
const parent = document.createElement("div");
const child = document.createElement("p");

parent.append(child); // result: <div><p></p></div>


// 한번에 여러 개의 자식 요소를 설정할 수 있음
const div = document.createElement('div');
const span = document.createElement('span');
const p = document.createElement('p');

document.doby.append(div, 'hello', span, p);

// result
<body>
	<div></div>
	hello
	<span></span>
	<p></p>
</body>

 

 

✔ 완성 화면

https://p3skgm.csb.app/

 

 

 

반응형