노마드코더 챌린지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' 카테고리의 다른 글
[드림코딩] 윈도우 사이즈 가져오기 (0) | 2021.09.21 |
---|---|
[노마드코더] 바닐라JS 챌린지 - 랜덤 그라데이션 백그라운드 (0) | 2021.09.02 |
[노마드코더] 바닐라JS 챌린지 - 크리스마스 이브 D-day 계산기 (0) | 2021.09.02 |
[노마드코더] 바닐라JS 챌린지 - 숫자 입력 게임 (0) | 2021.08.31 |
[노마드코더] 바닐라JS 챌린지 - 마우스 이벤트, 윈도우 사이즈 - 글자 색변 경하기 (0) | 2021.08.27 |
[노마드코더] 바닐라JS 챌린지 - resize발생시 배경화면 색 변경