본문 바로가기
Front-end/Javascript 실습

web APIs 윈도우 좌표 찾기

by warrior.p 2022. 3. 12.
<!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>
    <style>
      body {
        background-color: black;
      }
      div {
        width: 250px;
        height: 250px;
        margin-bottom: 5px;
        background-color: yellow;
        border-radius: 10%;
      }
      .special {
        background-color: salmon;
      }
    </style>
  </head>
  <body>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div class="special"></div>
    <div></div>
    <div></div>
    <div></div>
    <script>
      const special = document.querySelector('.special');
      special.addEventListener('click', event => {
        const rect = special.getBoundingClientRect();
        console.log(rect);
        console.log(`client: ${event.clientX}, ${event.clientY}`);
        console.log(`page: ${event.pageX}, ${event.pageY}`);
      });
    </script>
  </body>
</html>

- const rect = special.getBoundingClientRect() 는
 special 객체의 getBoundingClientRect를 호출해서 rect에 값을 담아두는 것.

- console.log(`client: ${event.clientX}, ${event.clientY}`);
 console.log(`client: ${event.pageX}, ${event.pageY}`);는

 클릭 발생 시 MouseEvent로부터 값을 가져와 출력

 

 

MouseEvent - Web API | MDN

MouseEvent 인터페이스는 특정 지점을 가리키는 장치를 통해 발생하는 이벤트를 의미한다 (마우스 등). 주로 사용되는 이벤트로는 click, dblclick (en-US), mouseup (en-US), mousedown (en-US)가 있다.

developer.mozilla.org