노마드코더 챌린지5일

  • if... else : 조건식의 결과에 따라 {}로 묶인 블록의 실행 여부를 결정하는 조건문입니다
  • classList : 요소에 적용된 클래스들의 이름을 리스트 형태로 반환해 줍니다
  • remove : classList의 메서드입니다. classList를 통해 반환된 리스트 중에서 원하는 클래스를 제거할 수 있습니다
  • add : classList의 메서드입니다. classList의 리스트에 원하는 클래스를 추가할 수 있습니다.
  • innerWidth : 브라우저의 가로 길이를 나타내는 Window 객체의 프로퍼티입니다.

 

css 없이 구현

const colors = ["#1abc9c", "#3498db", "#9b59b6", "#f39c12", "#e74c3c"];

function handleWindowResize() {
  const intViewportWidth = window.innerWidth;

  if (intViewportWidth <= 500) {
    document.body.style.backgroundColor = colors[1];
  } else if (intViewportWidth <= 700) {
    document.body.style.backgroundColor = colors[2];
  } else {
    document.body.style.backgroundColor = colors[3];
  }
}

document.body.style.backgroundColor = colors[0];

window.addEventListener("resize", handleWindowResize);

 

css - class 추가

.active1 {
  background-color: #1abc9c;
}
.active2 {
  background-color: #3498db;
}
.active3 {
  background-color: #9b59b6;
}
.active4 {
  background-color: #f39c12;
}

 

classList로 구현

function handleWindowResize() {
  const intViewportWidth = window.innerWidth;

  document.body.classList.remove("active1");
  document.body.classList.remove("active2");
  document.body.classList.remove("active3");

  if (intViewportWidth <= 500) {
    document.body.classList.add("active1");
  } else if (intViewportWidth <= 700) {
    document.body.classList.add("active2");
  } else {
    document.body.classList.add("active3");
  }
}

handleWindowResize();

window.addEventListener("resize", handleWindowResize);

 

toggle로 구현

function handleWindowResize() {
  const intViewportWidth = window.innerWidth;

  document.body.classList.toggle("active1", intViewportWidth <= 500);
  document.body.classList.toggle(
    "active2",
    intViewportWidth > 500 && intViewportWidth <= 700
  );
  document.body.classList.toggle("active3", intViewportWidth > 700);
}

handleWindowResize();

window.addEventListener("resize", handleWindowResize);
[노마드코더] 바닐라JS 챌린지 - resize발생시 배경화면 색 변경