728x90
반응형
오늘의 과제!
화면 사이즈를 변경하면 배경색이 바뀌도록 해보자.
body에 클래스를 적용하여 css를 통해 배경색을 여러 종류로 설정한 후
js를 통해 resize시 배경색을 변경하는 함수를 만들자.
먼저
.html
<body> 태그에 class를 추가해놓자.
<body class="mediumSized">
사이즈를 변경할 것이고, 배경색을 컨트롤할 것이므로 이를 css에 설정한다.
.css
.smallSized{
background-color: blueviolet;
}
.mediumSized{
background-color: deepskyblue;
}
.bigSized{
background-color: darkorange;
}
세가지 사이즈에 적용할 배경색 컬러를 설정했다.
현재 body에 적용된 사이즈는 medium이며, small과 big을 변경될 것이다.
이제 함수를 만들어보자.
.js
const body = document.body;
const width = window.innerWidth;
if (width > 1100){
body.classList.add("bigSized");
body.classList.remove("mediumSized");
} else if (width >= 700 && width <= 1100){
body.classList.add("mediumSized");
body.classList.remove("bigSized","smallSized");
} else {
body.classList.add("smallSized");
body.classList.remove("mediumSized");
}
창의 가로 사이즈를 가져오는 것은 window.innerwidth이다.
이를 width 변수에 할당하고,
각각의 조건을 만든다.
1. 1100 보다 클 경우
2. 700 보다 크고, 1100보다 작을 경우
3. 나머지 경우 (700보다 작은 경우 모두 포함)
body.classList.add("클래스명") : 클래스를 body에 추가하라
body.classList.remove("클래스명") : 클래스를 body에서 제거하라
각각 상황에 맞게 클래스를 현재에서 변화를 주도록 추가하고 제거하도록 한다.
const body = document.body;
const SMALL = "smallSized";
const MEDIUM = "mediumSized";
const BIG = "bigSized";
function handleResize(){
const width = window.innerWidth;
if (width > 1100){
body.classList.add(BIG);
body.classList.remove(MEDIUM);
} else if (width >= 700 && width <= 1100){
body.classList.add(MEDIUM);
body.classList.remove(BIG,SMALL);
} else {
body.classList.add(SMALL);
body.classList.remove(MEDIUM);
}
}
window.addEventListener("resize", handleResize);
마지막으로 사이즈에 클래스명을 변수로 할당해서 정리하고,
이벤트 리스너를 넣어준 뒤 함수를 만들어주었다.
BR.h
728x90
반응형
'Javascript: to do list' 카테고리의 다른 글
06 Document 도큐멘트에 대한 이해 (0) | 2023.05.30 |
---|---|
EX. 마우스 움직임에 반응하는 텍스트 만들기 (0) | 2023.05.30 |
05 Condition 조건문 연습하기 (0) | 2023.05.30 |
04 Function에서 Return의 의미 (0) | 2023.05.30 |
03 Function으로 계산식 만들기 (0) | 2023.05.30 |