Programing

브라우저의 뷰포트를 기준으로 요소의 최상위 위치를 얻는 방법은 무엇입니까?

lottogame 2020. 6. 18. 07:55
반응형

브라우저의 뷰포트를 기준으로 요소의 최상위 위치를 얻는 방법은 무엇입니까?


브라우저의 뷰포트 (페이지 전체가 아닌 페이지가 표시되는 뷰포트)를 기준으로 요소의 위치를 ​​가져 오려고합니다. JavaScript로 어떻게 이것을 할 수 있습니까?

많은 감사


기존 답변은 이제 구식입니다. 기본 getBoundingClientRect()방법은 꽤 오랫동안 사용되어 왔으며 질문이 요구하는 것을 정확하게 수행합니다. 또한 모든 브라우저에서 지원됩니다 (IE 5 포함).

에서 MDN 페이지 :

반환 값은 TextRectangle 객체로, 뷰포트의 왼쪽 상단을 기준으로 왼쪽 상단을 기준으로 테두리 상자를 설명하는 읽기 전용 왼쪽, 위쪽, 오른쪽 및 아래쪽 속성을 픽셀 단위로 포함합니다 .

당신은 그렇게 사용합니다 :

var viewportOffset = el.getBoundingClientRect();
// these are relative to the viewport, i.e. the window
var top = viewportOffset.top;
var left = viewportOffset.left;

필자의 경우 스크롤과 관련하여 안전하기 위해 window.scroll을 방정식에 추가했습니다.

var element = document.getElementById('myElement');
var topPos = element.getBoundingClientRect().top + window.scrollY;
var leftPos = element.getBoundingClientRect().left + window.scrollX;

그러면 스크롤 된 경우에도 문서에서 요소의 실제 상대 위치를 얻을 수 있습니다.


편집 : 페이지 스크롤을 설명하는 코드를 추가하십시오.

function findPos(id) {
    var node = document.getElementById(id);     
    var curtop = 0;
    var curtopscroll = 0;
    if (node.offsetParent) {
        do {
            curtop += node.offsetTop;
            curtopscroll += node.offsetParent ? node.offsetParent.scrollTop : 0;
        } while (node = node.offsetParent);

        alert(curtop - curtopscroll);
    }
}

id 인수는 오프셋을 원하는 요소의 id입니다. quirksmode 포스트 에서 적응시키는 .


var element =  document.querySelector('selector');
var bodyRect = document.body.getBoundingClientRect(),
    elemRect = element.getBoundingClientRect(),
    offset   = elemRect.top - bodyRect.top;

당신은 시도 할 수 있습니다:

node.offsetTop - window.scrollY

뷰포트 메타 태그가 정의 된 Opera에서 작동합니다.


jQuery는 이것을 매우 우아하게 구현합니다. jQuery의 소스를 보면 offset기본 구현 방법을 알 수 있습니다.

var rect = elem.getBoundingClientRect();
var win = elem.ownerDocument.defaultView;

return {
    top: rect.top + win.pageYOffset,
    left: rect.left + win.pageXOffset
};

페이지 의 함수 는 브라우저보기 포트를 기준으로 전달 된 요소의 상단, 왼쪽, 높이 및 너비 좌표가있는 사각형을 반환합니다.

    localToGlobal: function( _el ) {
       var target = _el,
       target_width = target.offsetWidth,
       target_height = target.offsetHeight,
       target_left = target.offsetLeft,
       target_top = target.offsetTop,
       gleft = 0,
       gtop = 0,
       rect = {};

       var moonwalk = function( _parent ) {
        if (!!_parent) {
            gleft += _parent.offsetLeft;
            gtop += _parent.offsetTop;
            moonwalk( _parent.offsetParent );
        } else {
            return rect = {
            top: target.offsetTop + gtop,
            left: target.offsetLeft + gleft,
            bottom: (target.offsetTop + gtop) + target_height,
            right: (target.offsetLeft + gleft) + target_width
            };
        }
    };
        moonwalk( target.offsetParent );
        return rect;
}

Thanks for all the answers. It seems Prototype already has a function that does this (the page() function). By viewing the source code of the function, I found that it first calculates the element offset position relative to the page (i.e. the document top), then subtracts the scrollTop from that. See the source code of prototype for more details.


I am assuming an element having an id of btn1 exists in the web page, and also that jQuery is included. This has worked across all modern browsers of Chrome, FireFox, IE >=9 and Edge. jQuery is only being used to determine the position relative to document.

var screenRelativeTop =  $("#btn1").offset().top - (window.scrollY || 
                                            window.pageYOffset || document.body.scrollTop);

var screenRelativeLeft =  $("#btn1").offset().left - (window.scrollX ||
                                           window.pageXOffset || document.body.scrollLeft);

Sometimes getBoundingClientRect() object's property value shows 0 for IE. In that case you have to set display = 'block' for the element. You can use below code for all browser to get offset.

Extend jQuery functionality :

(function($) {
    jQuery.fn.weOffset = function () {
        var de = document.documentElement;
        $(this).css("display", "block");
        var box = $(this).get(0).getBoundingClientRect();
        var top = box.top + window.pageYOffset - de.clientTop;
        var left = box.left + window.pageXOffset - de.clientLeft;
        return { top: top, left: left };
    };
}(jQuery));

Use :

var elementOffset = $("#" + elementId).weOffset();

참고URL : https://stackoverflow.com/questions/1350581/how-to-get-an-elements-top-position-relative-to-the-browsers-viewport

반응형