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. 함수 handlewindowResizedocument.body.clientWidth를 이용해 현재의 넓이를 알아내고 범위를 정해준다.

2. 범위마다 document.body.style.backgroundColor에 색상을 변경해준다.

3. 마지막에 window.addEventListener("resize", handlewindowResize); addEventListener를 태워준다.

728x90
반응형