창기준 좌표, 문서기준 좌표

lee jae hwan·2022년 8월 12일

브라우저

목록 보기
21/39

요소노드의 좌표시스템 프로퍼티

  1. 창기준 : clientX/clientY
    창(window) 왼쪽 모서리를 기준으로 좌표를 계산(position:fixed와 유사)

  2. 문서기준 : pageX/pageY
    문서 왼쪽 모서리를 기준으로 좌표를 계산(position:absolute와 유사)


창기준 좌표얻기

elem.getBoundingClientRect()메서드는 elem을 감싸는 가장 작은 네모의 창기준 좌표를 DOMRect클래스의 객체를 반환한다.

DOMRect프로퍼티
x와 y – 요소를 감싸는 네모의 창 기준 X, Y 좌표
width와 height – 요소를 감싸는 네모의 너비, 높이(음수도 가능)
top과 bottom – 요소를 감싸는 네모의 위쪽 모서리, 아래쪽 모서리의 Y 좌표
left와 right – 요소를 감싸는 네모의 왼쪽 모서리, 오른쪽 모서리의 X 좌표



elementFromPoint(x, y)

document.elementFromPoint(x, y)을 호출하면 창 기준 좌표 (x, y)에서 가장 가까운 중첩 요소를 반환한다.



요소를 창 내 특정 좌표에 고정하기

요소 근처에 무언가를 표시할 때에는 getBoundingClientRect를 사용해 요소의 좌표를 얻고 CSS position, left/top(또는 right/bottom)으로 위치를 설정한다.

let div = document.querySelector('#example');

function createMessageUnder(elem, html) {
  let coord = elem.getBoundingClientRect(); 
   let t = document.createElement('div');
   t.append(html);
   t.style.position = 'fixed';
   t.style.left = coord.left+'px';
   t.style.top = coord.bottom+'px';
   document.body.append(t);
 }

 createMessageUnder(div, '독도는 우리땅!');




문서기준좌표

문서 내 특정 좌표에 무언가를 위치시키고 싶을 땐 position:absolute와 top,left를 사용하면 스크롤 이동에 상관없이 해당 요소를 문서의 한 좌표에 머물게 할 수 있다.

먼저 원하는 위치의 문서기준좌표를 알아야 한다.

그런데 요소의 문서기준좌표를 제공하는 표준메서드가 아직 없지만 쉽게 코드를 작성할 수 있다.

창기준좌표와 문서기준좌표는 다음 수식으로 연관되어 있다.
pageY = elem.getBoundingClientRect().y + 문서에서 세로방향 스크롤에 의해 밀려난 부분의 높이
pageX = elem.getBoundingClientRect().x + 문서에서 가로방향 스크롤에 의해 밀려난 부분의 너비

function getCoords(elem) {
  let box = elem.getBoundingClientRect();

  return {
    top: box.top + window.pageYOffset,
    right: box.right + window.pageXOffset,
    bottom: box.bottom + window.pageYOffset,
    left: box.left + window.pageXOffset
  };
}
function createMessageUnder(elem, html) {
  let message = document.createElement('div');
  message.style.cssText = "position:absolute; color: red";

  let coords = getCoords(elem);

  message.style.left = coords.left + "px";
  message.style.top = coords.bottom + "px";

  message.innerHTML = html;

  return message;
}

0개의 댓글