Window, resize event๋ฅผ ๊ณต๋ถํ๋ฉด์ ์์ฑํ๋ ์ฝ๋๋ฅผ ๋ธ๋ก๊ทธ์๋ ์ ์ฅ์ฉ์ผ๋ก ์ฌ๋ ค๋ณด์!
1. ๋ธ๋ผ์ฐ์ width size์ ๋ฐ๋ผ ๋ฐฑ๊ทธ๋ผ์ด๋ ์์์ด ๋ฐ๋๋ ์ฝ๋.
function changeColor() {
const width = window.innerWidth;
console.log(width);
if (width <= 750) {
document.body.style.background = "yellow";
} else if (width > 750 && width <= 1300) {
document.body.style.background = "purple";
} else {
document.body.style.background = "white";
}
}
window.addEventListener("resize", changeColor);
๋ฐฑ๊ทธ๋ผ์ด๋ ์์ ๋ฐ๊พผ๋ค๊ณ ๊ฒ์์ ๊ฝค๋ ํ์๋ค..๐
2. ๋ฒํผ์ ํด๋ฆญํ๋ฉด ๋ฐฑ๊ทธ๋ผ์ด๋ ์์์ด ๋ฐ๋๋ ์ฝ๋
<!--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" />
<title>Document</title>
</head>
<body>
<button id="yellowBtn">yellow</button>
<button id="purpleBtn">purple</button>
<script src="index.js"></script>
</body>
</html>
//Javascript
const yellowBtn = document.querySelector("#yellowBtn");
const purpleBtn = document.querySelector("#purpleBtn");
function ChangeYellowColor() {
document.body.style.backgroundColor = "yellow";
}
function ChangePurpleColor() {
document.body.style.backgroundColor = "purple";
}
yellowBtn.addEventListener("click", ChangeYellowColor);
purpleBtn.addEventListener("click", ChangePurpleColor);
3. ๊ทธ๋ฆฌ๊ณ ์๋ ์ฝ๋๋ classList
์ add๋ฅผ ํจ๊ป ์ฌ์ฉํด๋ณธ ์ฝ๋.
<!--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>
<div id="greet">Hello!</div>
</div>
<script src="index.js"></script>
</body>
</html>
/*CSS*/
body {
margin: 0;
}
div {
width: 100vw;
height: 100vh;
}
#greet {
font-size: 50px;
font-weight: bold;
color: white;
}
//Javascript
const colors = ["blue", "orange", "purple", "white"];
const div = document.querySelector("div");
div.style.backgroundColor = colors[0];
function changeColor() {
const width = window.innerWidth;
if (width <= 750) {
div.classList.add("blueColor");
div.style.backgroundColor = colors[0];
} else if (width > 750 && width <= 1300) {
div.classList.add("orangeColor");
div.style.backgroundColor = colors[1];
} else {
div.classList.add("purpleColor");
div.style.backgroundColor = colors[2];
}
}
window.addEventListener("resize", changeColor);
nice~ =D