728x90
반응형
반응형
Window event인 resize를 이용하여 화면 넓이에 따른 배경색이 변하는 웹을 만들어보자!
1. HTML
<!DOCTYPE html>
<html>
<head>
<title>Resize</title>
<meta charset="UTF-8" />
</head>
<h1 id="text">HELLO!</h1>
<body>
<script src="src/index.js"></script>
</body>
</html>
2. JavaScript
function handlewindowResize() {
const bodyWidth = document.body.clientWidth;
//console.log(bodyWidth);
if (bodyWidth < 300) {
document.body.style.backgroundColor = "pink";
document.getElementById("text").innerText = "Pink";
} else if (bodyWidth < 400) {
document.body.style.backgroundColor = "yellow";
document.getElementById("text").innerText = "Yellow";
} else if (bodyWidth < 500) {
document.body.style.backgroundColor = "red";
document.getElementById("text").innerText = "Red";
} else if (bodyWidth < 600) {
document.body.style.backgroundColor = "darkslategrey";
document.getElementById("text").innerText = "Darkslategrey";
} else if (bodyWidth < 700) {
document.body.style.backgroundColor = "cornflowerblue";
document.getElementById("text").innerText = "Cornflowerblue";
} else {
document.body.style.backgroundColor = "indianred";
document.getElementById("text").innerText = "Indianred";
}
}
window.addEventListener("resize", handlewindowResize);
1. 함수 handlewindowResize에 document.body.clientWidth를 이용해 현재의 넓이를 알아내고 범위를 정해준다.
2. 범위마다 document.body.style.backgroundColor에 색상을 변경해준다.
3. 마지막에 window.addEventListener("resize", handlewindowResize); addEventListener를 태워준다.
728x90
반응형
'Coding With Jina > JavaScript' 카테고리의 다른 글
[자바스크립트] 단항 더하기 연산자(+) (0) | 2024.04.29 |
---|---|
[자바스크립트] 비구조화 할당/구조분해 할당 문법 const [a, b] (0) | 2024.04.29 |
[자바스크립트/ES6] for...in 문 / 배열객체마다 반복되는 실행문 (0) | 2024.04.23 |
[Node.js] 간단하게 Node와 NPM을 최신 버전으로 업데이트하기 (0) | 2024.04.08 |
[자바스크립트] 동기와 비동기 차이점 (2) | 2023.02.03 |