문서를 기준으로 요소의 위치 찾기
문서 / 본문 / 브라우저 창을 기준으로 요소 위치를 결정하는 가장 쉬운 방법은 무엇입니까?
지금은을 사용 .offsetLeft/offsetTop
하고 있지만이 방법은 부모 요소에 대한 상대적 위치 만 제공하므로 body / 브라우저 창 / 문서 위치에 상대적인 위치를 알기 위해 body 요소에 대한 부모 수를 결정해야합니다.
이 방법도 번거 롭습니다.
offsetParent
DOM의 최상위 수준까지 이동할 수 있습니다 .
function getOffsetLeft( elem )
{
var offsetLeft = 0;
do {
if ( !isNaN( elem.offsetLeft ) )
{
offsetLeft += elem.offsetLeft;
}
} while( elem = elem.offsetParent );
return offsetLeft;
}
다음 과 같이 DOM을 탐색하지 않고도 상단 및 왼쪽 을 얻을 수 있습니다 .
function getCoords(elem) { // crossbrowser version
var box = elem.getBoundingClientRect();
var body = document.body;
var docEl = document.documentElement;
var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft;
var clientTop = docEl.clientTop || body.clientTop || 0;
var clientLeft = docEl.clientLeft || body.clientLeft || 0;
var top = box.top + scrollTop - clientTop;
var left = box.left + scrollLeft - clientLeft;
return { top: Math.round(top), left: Math.round(left) };
}
를 사용 element.getBoundingClientRect()
하여 뷰포트를 기준으로 요소 위치를 검색 할 수 있습니다 .
그런 다음을 사용 document.documentElement.scrollTop
하여 뷰포트 오프셋을 계산합니다.
이 둘의 합은 문서에 상대적인 요소 위치를 제공합니다.
element.getBoundingClientRect().top + document.documentElement.scrollTop
document-offset
( 타사 스크립트 ) 흥미롭고 여기 다른 답변의 접근 방식을 활용하는 것 같습니다.
예:
var offset = require('document-offset')
var target = document.getElementById('target')
console.log(offset(target))
// => {top: 69, left: 108}
나는 사용하는 것이 좋습니다
element.getBoundingClientRect()
offsetLeft , offsetTop 및 offsetParent를 통한 수동 오프셋 계산 대신 여기에 제안 된대로 . 여기에 제안 된대로 일부 상황 *에서 수동 순회는 잘못된 결과를 생성합니다. 이 Plunker 참조 : http://plnkr.co/pC8Kgj
* 요소가 정적 (= 기본값) 위치를 갖는 스크롤 가능한 부모 내부에있을 때.
문서를 기준으로 한 요소의 다양한 위치에 대한 x 및 y 좌표를 얻으려는 사람들을 위해.
const getCoords = (element, position) => {
const { top, left, width, height } = element.getBoundingClientRect();
let point;
switch (position) {
case "top left":
point = {
x: left + window.pageXOffset,
y: top + window.pageYOffset
};
break;
case "top center":
point = {
x: left + width / 2 + window.pageXOffset,
y: top + window.pageYOffset
};
break;
case "top right":
point = {
x: left + width + window.pageXOffset,
y: top + window.pageYOffset
};
break;
case "center left":
point = {
x: left + window.pageXOffset,
y: top + height / 2 + window.pageYOffset
};
break;
case "center":
point = {
x: left + width / 2 + window.pageXOffset,
y: top + height / 2 + window.pageYOffset
};
break;
case "center right":
point = {
x: left + width + window.pageXOffset,
y: top + height / 2 + window.pageYOffset
};
break;
case "bottom left":
point = {
x: left + window.pageXOffset,
y: top + height + window.pageYOffset
};
break;
case "bottom center":
point = {
x: left + width / 2 + window.pageXOffset,
y: top + height + window.pageYOffset
};
break;
case "bottom right":
point = {
x: left + width + window.pageXOffset,
y: top + height + window.pageYOffset
};
break;
}
return point;
};
용법
getCoords(document.querySelector('selector'), 'center')
getCoords(document.querySelector('selector'), 'bottom right')
getCoords(document.querySelector('selector'), 'top center')
I've found the following method to be the most reliable when dealing with edge cases that trip up offsetTop/offsetLeft.
function getPosition(element) {
var clientRect = element.getBoundingClientRect();
return {left: clientRect.left + document.body.scrollLeft,
top: clientRect.top + document.body.scrollTop};
}
http://www.quirksmode.org/js/findpos.html Explains the best way to do it, all in all, you are on the right track you have to find the offsets and traverse up the tree of parents.
If you don't mind using jQuery, then you can use offset()
function. Refer to documentation if you want to read up more about this function.
참고URL : https://stackoverflow.com/questions/5598743/finding-elements-position-relative-to-the-document
'developer tip' 카테고리의 다른 글
장고 내비게이션 (0) | 2020.08.21 |
---|---|
C ++ 11 지원을 어떻게 확인합니까? (0) | 2020.08.21 |
URL에서 Windows 배치 파일 다운로드 (0) | 2020.08.21 |
표준 10 자리 전화 번호와 일치하는 정규식 (0) | 2020.08.21 |
Guzzle 예외 처리 및 HTTP 본문 가져 오기 (0) | 2020.08.21 |