etc./StackOverFlow

브라우저 창을 기준으로 HTML 요소의 위치(X,Y) 검색

청렴결백한 만능 재주꾼 2021. 12. 21. 22:08
반응형

질문자 :monaung


브라우저 창을 기준으로 JavaScript에서 imgdiv 와 같은 HTML 요소의 X 및 Y 위치를 가져오는 방법을 알고 싶습니다.



element.getBoundingClientRect() 를 사용하는 것입니다.

 var rect = element.getBoundingClientRect(); console.log(rect.top, rect.right, rect.bottom, rect.left);

Internet Explorer는 관심이 있는 한 이를 지원했으며 마침내 CSSOM Views 에서 표준화되었습니다. 다른 모든 브라우저 는 오래 전에 이를 채택했습니다.

일부 브라우저는 비표준이지만 높이 및 너비 속성도 반환합니다. 이전 브라우저 호환성이 걱정되는 경우 최적화된 저하 구현에 대한 이 답변의 개정판을 확인하십시오.

element.getBoundingClientRect() 의해 반환된 값은 뷰포트에 상대적입니다. 다른 요소와 관련하여 필요한 경우 다른 직사각형에서 하나의 직사각형을 빼면 됩니다.

 var bodyRect = document.body.getBoundingClientRect(), elemRect = element.getBoundingClientRect(), offset = elemRect.top - bodyRect.top; alert('Element is ' + offset + ' vertical pixels from <body>');

Andy E

라이브러리는 요소에 대한 정확한 오프셋을 얻기 위해 약간의 길이로 이동합니다.
여기에 내가 시도한 모든 상황에서 작업을 수행하는 간단한 기능이 있습니다.

 function getOffset( el ) { var _x = 0; var _y = 0; while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) { _x += el.offsetLeft - el.scrollLeft; _y += el.offsetTop - el.scrollTop; el = el.offsetParent; } return { top: _y, left: _x }; } var x = getOffset( document.getElementById('yourElId') ).left;

meouw

이 함수는 전체 문서(페이지)에 상대적인 요소의 위치를 반환합니다.

 function getOffset(el) { const rect = el.getBoundingClientRect(); return { left: rect.left + window.scrollX, top: rect.top + window.scrollY }; }

이것을 사용하여 X 위치를 얻을 수 있습니다.

 getOffset(element).left

... 또는 Y 위치:

 getOffset(element).top

타입스크립트 버전:

 export type ElementOffset = { left: number; top: number }; /** * Returns an element's position relative to the whole document (page). * * If the element does not exist, returns O/O (top-left window corner). * * @example getOffset(document.getElementById('#element')); * * @param el * @see https://stackoverflow.com/a/28222246/2391795 */ export const getElementOffset = (el: Element | null): ElementOffset => { const rect = el?.getBoundingClientRect(); return { left: (rect?.left || 0) + window?.scrollX, top: (rect?.top || 0) + window?.scrollY, }; }; export default getElementOffset;

Adam Grant

javascript에서만 수행하려면getBoundingClientRect() 사용하는 몇 가지 라이너가 있습니다.

 window.scrollY + document.querySelector('#elementId').getBoundingClientRect().top // Y window.scrollX + document.querySelector('#elementId').getBoundingClientRect().left // X

첫 번째 줄은 문서를 기준으로 Y를 말하는 offsetTop 두 번째 줄은 문서에 상대적인 X라고 말하는 offsetLeft

getBoundingClientRect() 는 창의 뷰포트를 기준으로 요소의 위치를 반환하는 자바스크립트 함수입니다.


Mustkeem K

대부분의 브라우저에서 HTML 요소에는 다음이 포함됩니다.

 offsetLeft offsetTop

레이아웃이 있는 가장 가까운 부모에 상대적인 요소의 위치를 지정합니다. offsetParent 속성이 있으면 이 부모에 자주 액세스할 수 있습니다.

IE와 FF3는

 clientLeft clientTop

이러한 속성은 덜 일반적이며 부모 클라이언트 영역과 함께 요소 위치를 지정합니다(패딩된 영역은 클라이언트 영역의 일부이지만 테두리와 여백은 그렇지 않음).


AnthonyWJones

페이지에 최소한 "DIV"가 포함된 경우 meouw에서 제공하는 함수는 현재 페이지 제한을 초과하는 "Y" 값을 던집니다. 정확한 위치를 찾으려면 offsetParent와 parentNode를 모두 처리해야 합니다.

아래 주어진 코드를 시도하십시오(FF2에 대해 확인됨).

 var getAbsPosition = function(el){ var el2 = el; var curtop = 0; var curleft = 0; if (document.getElementById || document.all) { do { curleft += el.offsetLeft-el.scrollLeft; curtop += el.offsetTop-el.scrollTop; el = el.offsetParent; el2 = el2.parentNode; while (el2 != el) { curleft -= el2.scrollLeft; curtop -= el2.scrollTop; el2 = el2.parentNode; } } while (el.offsetParent); } else if (document.layers) { curtop += el.y; curleft += el.x; } return [curtop, curleft]; };

Refik Ayata

Element.prototype 에 두 가지 속성을 추가하여 요소의 상단/왼쪽을 가져올 수 있습니다.

 Object.defineProperty( Element.prototype, 'documentOffsetTop', { get: function () { return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop : 0 ); } } ); Object.defineProperty( Element.prototype, 'documentOffsetLeft', { get: function () { return this.offsetLeft + ( this.offsetParent ? this.offsetParent.documentOffsetLeft : 0 ); } } );

이것은 다음과 같이 호출됩니다.

 var x = document.getElementById( 'myDiv' ).documentOffsetLeft;

다음은 결과를 jQuery의 offset().top.left 와 비교하는 데모입니다. http://jsfiddle.net/ThinkingStiff/3G7EZ/


ThinkingStiff

재귀 함수를 사용하지 않고 페이지에 상대적인 위치를 효율적으로 검색하려면: (IE도 포함)

 var element = document.getElementById('elementId'); //replace elementId with your element's Id. var rect = element.getBoundingClientRect(); var elementLeft,elementTop; //x and y var scrollTop = document.documentElement.scrollTop? document.documentElement.scrollTop:document.body.scrollTop; var scrollLeft = document.documentElement.scrollLeft? document.documentElement.scrollLeft:document.body.scrollLeft; elementTop = rect.top+scrollTop; elementLeft = rect.left+scrollLeft;

Abdul Rahim Haddad

이와 같이 요소의 ID를 전달하면 왼쪽 또는 위쪽을 반환하므로 이를 결합할 수도 있습니다.

1) 왼쪽 찾기

 function findLeft(element) { var rec = document.getElementById(element).getBoundingClientRect(); return rec.left + window.scrollX; } //call it like findLeft('#header');

2) 상단 찾기

 function findTop(element) { var rec = document.getElementById(element).getBoundingClientRect(); return rec.top + window.scrollY; } //call it like findTop('#header');

또는 3) 왼쪽과 위쪽을 함께 찾습니다.

 function findTopLeft(element) { var rec = document.getElementById(element).getBoundingClientRect(); return {top: rec.top + window.scrollY, left: rec.left + window.scrollX}; } //call it like findTopLeft('#header');

Alireza

jQuery .offset() 은 첫 번째 요소의 현재 좌표를 가져오거나 문서를 기준으로 일치하는 요소 집합에서 모든 요소의 좌표를 설정합니다.


akauppi

브라우저에 독립적인 방식으로 이러한 정보(및 훨씬 더 많은!)를 반환하는 기능이 있는 JavaScript 프레임워크를 사용하면 더 나은 서비스를 받을 수 있습니다. 다음은 몇 가지입니다.

이러한 프레임워크를 사용하면 $('id-of-img').top 과 같은 작업을 수행하여 이미지의 y-픽셀 좌표를 얻을 수 있습니다.


Shalom Craimer

/** * * @param {HTMLElement} el * @return {{top: number, left: number}} */ function getDocumentOffsetPosition(el) { var position = { top: el.offsetTop, left: el.offsetLeft }; if (el.offsetParent) { var parentPosition = getDocumentOffsetPosition(el.offsetParent); position.top += parentPosition.top; position.left += parentPosition.left; } return position; }

답변에 대해 ThinkingStiff 에게 감사드립니다. 이것은 또 다른 버전일 뿐입니다.


Văn Quyết

@meouw의 답변을 가져와 테두리를 허용하는 clientLeft에 추가한 다음 세 가지 버전을 만들었습니다.

getAbsoluteOffsetFromBody - @meouw와 유사하며 문서의 본문 또는 html 요소에 상대적인 절대 위치를 가져옵니다(특수 모드에 따라 다름)

getAbsoluteOffsetFromGivenElement - 주어진 요소(relativeEl)에 상대적인 절대 위치를 반환합니다. 주어진 요소는 요소 el을 포함해야 하며, 그렇지 않으면 getAbsoluteOffsetFromBody와 동일하게 작동합니다. 이것은 다른 (알려진) 요소(선택적으로 노드 트리의 여러 노드) 내에 두 개의 요소가 포함되어 있고 동일한 위치로 만들려는 경우에 유용합니다.

getAbsoluteOffsetFromRelative - position: relative가 있는 첫 번째 부모 요소에 상대적인 절대 위치를 반환합니다. 이것은 같은 이유로 getAbsoluteOffsetFromGivenElement와 유사하지만 첫 번째 일치하는 요소까지만 이동합니다.

 getAbsoluteOffsetFromBody = function( el ) { // finds the offset of el from the body or html element var _x = 0; var _y = 0; while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) { _x += el.offsetLeft - el.scrollLeft + el.clientLeft; _y += el.offsetTop - el.scrollTop + el.clientTop; el = el.offsetParent; } return { top: _y, left: _x }; } getAbsoluteOffsetFromGivenElement = function( el, relativeEl ) { // finds the offset of el from relativeEl var _x = 0; var _y = 0; while( el && el != relativeEl && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) { _x += el.offsetLeft - el.scrollLeft + el.clientLeft; _y += el.offsetTop - el.scrollTop + el.clientTop; el = el.offsetParent; } return { top: _y, left: _x }; } getAbsoluteOffsetFromRelative = function( el ) { // finds the offset of el from the first parent with position: relative var _x = 0; var _y = 0; while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) { _x += el.offsetLeft - el.scrollLeft + el.clientLeft; _y += el.offsetTop - el.scrollTop + el.clientTop; el = el.offsetParent; if (el != null) { if (getComputedStyle !== 'undefined') valString = getComputedStyle(el, null).getPropertyValue('position'); else valString = el.currentStyle['position']; if (valString === "relative") el = null; } } return { top: _y, left: _x }; }

특히 스크롤과 관련하여 여전히 문제가 있는 경우 http://www.greywyvern.com/?post=331을 살펴보십시오. getStyle에서 브라우저가 동작한다고 가정하면 문제가 없는 코드 중 하나 이상을 발견했습니다. , 그러나 나머지는 전혀 테스트하지 않았습니다.


James Carlyle-Clarke

jQuery를 사용하는 경우 차원 플러그인 이 우수하고 원하는 것을 정확하게 지정할 수 있습니다.

상대 위치, 절대 위치, 패딩 없는 절대 위치, 패딩 포함...

당신이 그것으로 할 수 있는 것이 많다고 말합시다.

또한 jQuery 사용의 장점은 파일 크기가 가볍고 사용이 간편하다는 점입니다. 나중에 jQuery 없이는 JavaScript로 돌아가지 않을 것입니다.


John_

jQuery를 사용하는 경우 다음과 같은 간단한 솔루션이 될 수 있습니다.

 <script> var el = $("#element"); var position = el.position(); console.log( "left: " + position.left + ", top: " + position.top ); </script>

Adam Boostani

작은 것과 작은 것의 차이

 function getPosition( el ) { var x = 0; var y = 0; while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) { x += el.offsetLeft - el.scrollLeft; y += el.offsetTop - el.scrollTop; el = el.offsetParent; } return { top: y, left: x }; }

예제 좌표 보기: http://javascript.info/tutorial/coordinates


KingRider

내가 찾은 가장 깔끔한 접근 방식은 jQuery의 offset 사용하는 기술의 단순화된 버전입니다. 다른 답변과 유사하게 getBoundingClientRect 시작합니다. 그런 다음 window documentElement 를 사용하여 스크롤 위치와 body 의 여백(종종 기본값)을 조정합니다.

 var rect = el.getBoundingClientRect(); var docEl = document.documentElement; var rectTop = rect.top + window.pageYOffset - docEl.clientTop; var rectLeft = rect.left + window.pageXOffset - docEl.clientLeft; 

 var els = document.getElementsByTagName("div"); var docEl = document.documentElement; for (var i = 0; i < els.length; i++) { var rect = els[i].getBoundingClientRect(); var rectTop = rect.top + window.pageYOffset - docEl.clientTop; var rectLeft = rect.left + window.pageXOffset - docEl.clientLeft; els[i].innerHTML = "<b>" + rectLeft + ", " + rectTop + "</b>"; }
 div { width: 100px; height: 100px; background-color: red; border: 1px solid black; } #rel { position: relative; left: 10px; top: 10px; } #abs { position: absolute; top: 250px; left: 250px; }
 <div id="rel"></div> <div id="abs"></div> <div></div>


James Montagne

이것은 내가 만들 수 있었던 최고의 코드입니다(jQuery의 offset()과 달리 iframe에서도 작동함). 웹킷이 약간 다른 동작을 하는 것 같습니다.

meouw의 의견을 기반으로:

 function getOffset( el ) { var _x = 0; var _y = 0; while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) { _x += el.offsetLeft - el.scrollLeft; _y += el.offsetTop - el.scrollTop; // chrome/safari if ($.browser.webkit) { el = el.parentNode; } else { // firefox/IE el = el.offsetParent; } } return { top: _y, left: _x }; }

Ron Reiter

이것은 많은 답변의 맨 아래에서 손실될 가능성이 매우 높지만 여기의 최상위 솔루션은 저에게 효과가 없었습니다.
내가 말할 수있는 한 다른 답변 중 어느 것도 도움이되지 않았습니다.

상황 :
HTML5 페이지에는 헤더 내부에 탐색 요소인 메뉴가 있었습니다(THE 헤더가 아니라 다른 요소의 헤더).
사용자가 스크롤하면 탐색이 상단에 고정되기를 원했지만 그 이전에는 헤더가 절대 위치에 있었습니다(그래서 다른 것을 약간 오버레이할 수 있었습니다).
.offsetTop은 절대 위치 요소이므로 변경되지 않을 것이기 때문에 위의 솔루션은 변경을 촉발하지 않았습니다. 또한 .scrollTop 속성은 단순히 최상위 요소의 맨 위였습니다... 즉, 0이고 항상 0이 됩니다.
이 두 가지를 사용하여 수행한 모든 테스트(getBoundingClientRect 결과와 동일)는 탐색 모음의 상단이 볼 수 있는 페이지의 상단으로 스크롤되었는지 여부를 알려주지 않습니다(다시 말하지만 콘솔에 보고된 대로 스크롤하는 동안 단순히 동일한 숫자를 유지했습니다. 발생).

해결책
나를위한 솔루션은

 window.visualViewport.pageTop

pageTop 속성 값은 화면의 볼 수 있는 섹션을 반영하므로 볼 수 있는 영역의 경계를 참조하여 요소가 있는 위치를 추적할 수 있습니다.

아마도 말할 필요도 없을 것입니다. 스크롤을 다룰 때마다 이 솔루션을 사용하여 스크롤되는 요소의 움직임에 프로그래밍 방식으로 응답할 것으로 예상합니다.
다른 사람을 돕기를 바랍니다.
중요 참고 사항: 이것은 현재 Chrome 및 Opera에서 작동하는 것으로 보입니다. Firefox(6-2018)에서는 확실히 작동하지 않습니다 ... Firefox가 visualViewport를 지원할 때까지는 이 방법을 사용하지 않는 것이 좋습니다. 나머지보다 더 의미).


업데이트:
이 솔루션에 대한 참고 사항입니다.
나는 여전히 "... 스크롤되는 요소의 움직임에 프로그래밍 방식으로 응답"하는 상황에서 매우 유용하다는 것을 발견했습니다. 해당됩니다. 내가 가진 문제에 대한 더 나은 해결책은 CSS를 사용하여 요소에 position:sticky를 설정하는 것이었습니다. 스티키를 사용하면 자바스크립트를 사용하지 않고도 요소를 맨 위에 유지할 수 있습니다.

업데이트01:
그래서 저는 다른 페이지에 대해 약간 복잡한 스크롤 설정(메시지의 일부로 스크롤되는 시차와 요소)에서 요소의 위치를 감지해야 하는 요구 사항이 있다는 것을 깨달았습니다. 나는 그 시나리오에서 다음이 내가 언제 무엇을 해야 할지 결정하는 데 활용한 가치를 제공한다는 것을 깨달았습니다.

 let bodyElement = document.getElementsByTagName('body')[0]; let elementToTrack = bodyElement.querySelector('.trackme'); trackedObjPos = elementToTrack.getBoundingClientRect().top; if(trackedObjPos > 264) { bodyElement.style.cssText = ''; }

이 답변이 이제 더 널리 유용하기를 바랍니다.


MER

요소의 총 오프셋을 얻으려면 모든 상위 오프셋을 재귀적으로 합산할 수 있습니다.

 function getParentOffset(el): number { if (el.offsetParent) { return el.offsetParent.offsetTop + getParentOffset(el.offsetParent); } else { return 0; } }

이 유틸리티 함수를 사용하면 dom 요소의 총 상단 오프셋은 다음과 같습니다.

 el.offsetTop + getParentOffset(el);

Kevin K.

구식 브라우저와 교차 호환되도록 이렇게 했습니다.

 // For really old browser's or incompatible ones function getOffsetSum(elem) { var top = 0, left = 0, bottom = 0, right = 0 var width = elem.offsetWidth; var height = elem.offsetHeight; while (elem) { top += elem.offsetTop; left += elem.offsetLeft; elem = elem.offsetParent; } right = left + width; bottom = top + height; return { top: top, left: left, bottom: bottom, right: right, } } function getOffsetRect(elem) { var box = elem.getBoundingClientRect(); var body = document.body; var docElem = document.documentElement; var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop; var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft; var clientTop = docElem.clientTop; var clientLeft = docElem.clientLeft; var top = box.top + scrollTop - clientTop; var left = box.left + scrollLeft - clientLeft; var bottom = top + (box.bottom - box.top); var right = left + (box.right - box.left); return { top: Math.round(top), left: Math.round(left), bottom: Math.round(bottom), right: Math.round(right), } } function getOffset(elem) { if (elem) { if (elem.getBoundingClientRect) { return getOffsetRect(elem); } else { // old browser return getOffsetSum(elem); } } else return null; }

JavaScript의 좌표에 대한 추가 정보: http://javascript.info/tutorial/coordinates


Bojan Kseneman

    
HTML program to show (x, y) of an element by dragging mouse over it you just copied it and use it on your own <!DOCTYPE html> <html> <head> <title> position of an element </title> <!-- scropt to get position --> <script type = "text/javascript"> function getPositionXY(element) { var rect = element.getBoundingClientRect(); document.getElementById('text').innerHTML = 'X: ' + rect.x + '<br>' + 'Y: ' + rect.y; } </script> </head> <body> <p>Move the mouse over the text</p> <div onmouseover = "getPositionXY(this)"> Position: <p id = 'text'></p> </div> </body> </html>


Azer8

element.offsetTopelement.offsetParent 를 재귀적으로 반복하기 위해 바닐라 JS를 사용하는 최신 1-라이너입니다.

기능:

 getTop = el => el.offsetTop + (el.offsetParent && getTop(el.offsetParent))

용법:

 const el = document.querySelector('#div_id'); const elTop = getTop(el)

이점:

현재 스크롤 위치에 관계없이 항상 절대 수직 오프셋을 반환합니다.


기존 구문:

 function getTop(el) { return el.offsetTop + (el.offsetParent && getTop(el.offsetParent)); }

Philipp

Andy E의 솔루션을 사용하여 사용자가 클릭한 테이블 행의 링크에 따라 부트스트랩 2 모달을 배치했습니다. 페이지는 Tapestry 5 페이지이며 아래 자바스크립트는 자바 페이지 클래스에서 가져옵니다.

자바스크립트:

 function setLinkPosition(clientId){ var bodyRect = document.body.getBoundingClientRect(), elemRect = clientId.getBoundingClientRect(), offset = elemRect.top - bodyRect.top; offset = offset + 20; $('#serviceLineModal').css("top", offset);

}

내 모달 코드:

 <div id="serviceLineModal" class="modal hide fade add-absolute-position" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="top:50%;"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button> <h3 id="myModalLabel">Modal header</h3> </div> <div class="modal-body"> <t:zone t:id="modalZone" id="modalZone"> <p>You selected service line number: ${serviceLineNumberSelected}</p> </t:zone> </div> <div class="modal-footer"> <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> <!-- <button class="btn btn-primary">Save changes</button> --> </div>

루프의 링크:

 <t:loop source="servicesToDisplay" value="service" encoder="encoder"> <tr style="border-right: 1px solid black;"> <td style="white-space:nowrap;" class="add-padding-left-and-right no-border"> <at:type="eventLink" t:event="serviceLineNumberSelected" t:context="service.serviceLineNumber" t:zone="pageZone" t:clientId="modalLink${service.serviceLineNumber}" onmouseover="setLinkPosition(this);"> <i class="icon-chevron-down"></i> <!-- ${service.serviceLineNumber} --> </a> </td>

그리고 페이지 클래스의 자바 코드:

 void onServiceLineNumberSelected(String number){ checkForNullSession(); serviceLineNumberSelected = number; addOpenServiceLineDialogCommand(); ajaxResponseRenderer.addRender(modalZone); } protected void addOpenServiceLineDialogCommand() { ajaxResponseRenderer.addCallback(new JavaScriptCallback() { @Override public void run(JavaScriptSupport javascriptSupport) { javascriptSupport.addScript("$('#serviceLineModal').modal('show');"); } }); }

이것이 누군가에게 도움이되기를 바랍니다.이 게시물이 도움이되었습니다.


Mark Espinoza

많은 연구와 테스트 후에 이것은 작동하는 것 같습니다

 function getPosition(e) { var isNotFirefox = (navigator.userAgent.toLowerCase().indexOf('firefox') == -1); var x = 0, y = 0; while (e) { x += e.offsetLeft - e.scrollLeft + (isNotFirefox ? e.clientLeft : 0); y += e.offsetTop - e.scrollTop + (isNotFirefox ? e.clientTop : 0); e = e.offsetParent; } return { x: x + window.scrollX, y: y + window.scrollY }; }

http://jsbin.com/xuvovalifo/edit?html,js,출력 참조


kernowcode

이것도 그냥 버려야겠다는 생각이 들었습니다.
이전 브라우저에서는 테스트할 수 없었지만 상위 3개 중 최신 버전에서는 작동합니다. :)

 Element.prototype.getOffsetTop = function() { return ( this.parentElement )? this.offsetTop + this.parentElement.getOffsetTop(): this.offsetTop; }; Element.prototype.getOffsetLeft = function() { return ( this.parentElement )? this.offsetLeft + this.parentElement.getOffsetLeft(): this.offsetLeft; }; Element.prototype.getOffset = function() { return {'left':this.getOffsetLeft(),'top':this.getOffsetTop()}; };

Duncan

이것은 JS에서 두 줄로 쉽습니다.

 var elem = document.getElementById("id"); alert(elem.getBoundingClientRect());

Talha Rafique

브라우저마다 테두리, 패딩, 여백 등을 다른 방식으로 렌더링하고 있기 때문입니다. 정확한 차원에서 원하는 모든 루트 요소에서 특정 요소의 위쪽 및 왼쪽 위치를 검색하는 작은 함수를 작성했습니다.

 function getTop(root, offset) { var rootRect = root.getBoundingClientRect(); var offsetRect = offset.getBoundingClientRect(); return offsetRect.top - rootRect.top; }

왼쪽 위치를 검색하려면 다음을 반환해야 합니다.

 return offsetRect.left - rootRect.left;

samadadi

왼쪽 및 위쪽에 대한 div의 위치 가져오기

 var elm = $('#div_id'); //get the div var posY_top = elm.offset().top; //get the position from top var posX_left = elm.offset().left; //get the position from left

Vishal Kumar

출처 : http:www.stackoverflow.com/questions/442404/retrieve-the-position-x-y-of-an-html-element-relative-to-the-browser-window

반응형