Modern Javscript Study - 문제풀이

유니·6일 전
0

문제풀이

문서2를 작성하면서 class를 이용한 여러가지 예시와 문제들을 보고 직접 풀어보았다.

알림만들기

샌드박스를 열었을 때 보이는 콘텐츠를 기반으로 <div class="notification"> 알림을 만들어주는 함수 showNotification(options)를 작성해봅시다.
이 알림은 1.5초 후에 자동으로 사라집니다. 옵션은 다음과 같습니다.
// 창의 오른쪽 상단에 "Hello"라는 텍스트가 담긴 요소를 보여줍니다.
showNotification({
  top: 10, // 창의 상단에서 10px 떨어진 위치에 표시합니다(기본값은 0px).
  right: 10, // 창의 오른쪽 가장자리에서 10px 떨어진 위치에 표시합니다(기본값은 0px).
  html: "Hello!", // 알림의 HTML입니다.
  className: "welcome" // div에 대한 추가 클래스입니다(선택 사항).
});

풀이

일단 샌드박스를 열었다는뜻은 페이지 가 로드될때 라는 뜻으로 생각하여 document.addEventListener의 이벤트 상태중 "DOMContentLoaded"를 이용하여 풀어보기로 했다.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./main.js"></script>
  </head>
  <body>
    <h1>hello world</h1>
  </body>
</html>
// 샌드박스를 열었을때 = DOMContentLoaded 때 이벤트 실행
document.addEventListener("DOMContentLoaded", function () {
  function showNotification(options) {
    let newNotification = document.createElement("div");
    newNotification.style.position = "fixed";
    newNotification.style.top = `${options.top}px`;
    newNotification.style.right = `${options.right}px`;
    newNotification.innerHTML = options.html;
    newNotification.classList.add(options.className);
    document.body.appendChild(newNotification);
    setTimeout(() => {
      newNotification.remove();
    }, 1500);
  }
  showNotification({
    top: 10,
    right: 10,
    html: "Hello!",
    className: "welcome",
  });
});

ScrollBottom 구하기

What's the scroll from the bottom?
중요도: 5
The elem.scrollTop property is the size of the scrolled out part from the top. How to get the size of the bottom scroll (let’s call it scrollBottom)?

Write the code that works for an arbitrary elem.

P.S. Please check your code: if there’s no scroll or the element is fully scrolled down, then it should return 0.

문제가 영어인데 해석하자면 elem.scrollTop은 top에서부터 스크롤된 사이즈를 구할 수 있다. bottom에서부터 스크롤된 사이즈는 어떻게 구할 수 있나?(scrollBottom이라 불린다.)

풀이

scrollBottom이라는것은 다르게 말하면 결국 남은 스크롤 길이 이기도 하다고 생각하여 아래와 같이 풀이하였다.

위와 같이 생각하면 ScrollBottom = ScrollHeight - ClientHeight - ScrollTop 이라는 것을 알 수 있다.

// elem이라는 Element가 있다고 가정하자.
const scrollBottom = elem.scrollHeight - elem.clientHeight - elem.scrollTop

공 가운데로 옮기기

Here’s how the source document looks:

What are coordinates of the field center?

Calculate them and use to place the ball into the center of the green field:

The element should be moved by JavaScript, not CSS.
The code should work with any ball size (10, 20, 30 pixels) and any field size, not be bound to the given values.
P.S. Sure, centering could be done with CSS, but here we want exactly JavaScript. Further we’ll meet other topics and more complex situations when JavaScript must be used. Here we do a “warm-up”.

첫번째 이미지의 공을 가운데로 옮겨라. 다만 CSS 는 사용하면 안된다. 오직 Javascript로만 움직여라.

풀이

일단 CSS를 이용해서 풀려했는데 해석해보니 CSS를 사용하면 안된다해서 너무 마음이 아팠다...
잔디밭을 하나의 거대한 div 라고 생각하고 해당 element의 중심점이 되는 값을 먼저 찾아보았다.

여기서 잔디 element 는 jandi, 공은 ball 이라고 가정한다.

// jandi의 clientwidth 의 반은 x축의 중간값, clientheight의 반은 y축의 중간값이다.
const jandiHalfWidth = jandi.clientWidth / 2;
const jandiHalfHeight = jandi.clientHeight / 2;

위와 같이 위치가 나왔는데 바로 적용시키면 안된다. 왜냐? 공이 가지고있는 크기가 있기 때문이다.
그러면 공 역시 반씩 더 땡겨져 와야하기때문에 공의 절반값도 구해야한다.

const ballHalfWidth = ball.clientWidth / 2;
const ballHalfHeight = ball.clientHalf / 2;

그러면 최종 좌표값은 아래와 같이 나온다.

const halfWidth = jandiHalfWidth - ballHalfWidth;
const halfHeight = jandiHalfHeight - ballHalfHeight;

마지막으로 ball의 style에게 중앙에 위치할수 있도록 위 값을 토대로 입력하면된다.

ball.style.position = "absolute" // absolute를 줘서 jandi 의 위에(공중에) 위치할 수 있게 한다.
ball.style.top = `${halfWidth}px`;
ball.style.left = `${halfHeight}px`;

후기

간단한 문제일 줄 알았는데 멍하니 풀다가 문제의 지문을 읽고 다시 푼 경우가 있었다.
덤으로 간만에 순수 javascript만으로 DOM을 컨트롤해서 재미있었다.

profile
Prospective Junior Front-end Developer

0개의 댓글

관련 채용 정보