HTML element coordinate positioning, these knowledge points must be mastered

Document and Viewport Coordinates

  Viewport coordinates are relative to the window, while document coordinates are relative to the entire document. For example, if an element's document-relative Y coordinate is 200px in document coordinates, and the user has scrolled the browser down 75px, then the element's Y coordinate in viewport coordinates is 200px - 75px = 125px.

  How do I get the position of the browser scrollbar? The pageXOffset and pageYOffset properties of the Window object provide these values ​​in all browsers except IE8 and earlier. IE and all modern browsers can also get the scrollbar position via the scrollLeft and scrollTop properties.

  The getScrollOffsets method of the following code gets the scrollbar position:
// put back the scrollbar position with the x and y properties of an object
function getScrollOffsets(w){
    w = w || window;
    //except IE 8 and earlier , other browsers support
    if(w.pageXOffset != null) return {x: w.pageXOffset, y: w.pageYOffset};
    //For IE in standard mode
    var d = w.document;
    if(document.compatMode == "CSS1Compat")
        return {x: d.documentElement.scrollLeft, y: d.documentElement.scrollTop};
    //For browsers in weird mode
    return { x: d.body.scrollLeft, y: d.body.scrollTop};
}   Sometimes
it is useful to be able to determine the size of the viewport, the following code simply queries the size of the viewport: //As an object The w and h properties return the size of the viewport function getViewportSize(w){     //Use the specified window, if there is no parameter, use the current window     w = w || window;     //Except IE8 and earlier versions, other Browsers can use     if(w.innerWidth != null)         return {w: w.innerWidth, h: w.innerHeight};     //For IE in standard mode (or any browser)     var d = w.document;     if(document.compatMode == "CSS1Compat")         return {w: d.documentElement.clientWidth, h: d.documentElement.clientHeight};     //For browsers in weird mode     return {w: d.body.clientWidth, h : d.body.clientHeight} ; }



















The above two examples have used scrollLeft, scrollTop, clientWidth, clientHeight. scrollLeft and scrollTop get the scrollbar position, while clientWidth and clientHeight get the size of the object.

Querying the Geometry of an Element The easiest way to


  determine the size and position of an element is to call its getBoundingClientRect() method. This method was introduced in IE5 and is now implemented in all current browsers. It takes no parameters and returns an object with left, right, top, bottom properties.

  This method returns the element's position in viewport coordinates. In order to convert to document coordinates that are still valid even after the user scrolls the browser window, a scroll offset needs to be added:
//The coordinate position of the element relative to the document
function getElementRect(e){
    var box = e.getBoundingClientRect();
    var offsets = getScrollOffsets();
    var x = box.left + offsets.x;
    var y = box.top + offsets.y;

    return {x:x, y: y};
} In
many browsers, getBoundingClientRect(
) The returned object also includes width and height properties. But not implemented in original IE. The width and height of an element can be calculated like this:
//Element size
function getElementSize(e){
    var box = getElementRect(e);
    var w = box.width || box.right - box.left;
    var h = box.height || box.bottom - box.top;

    return {w: w, h: h};
}
Copy code
Scroll element


  The previous getScrollOffsets method can query the position of the scroll bar. The scrollLeft and scrollTop properties of this example can be used to set the browser to scroll, but there is an easier way that has been supported since the earliest days of Javascript. The scrollTop() method of the Window object interfaces with the X and Y coordinates (document coordinates) of a point and sets them as the offset of the scroll bar. The following code scrolls the browser to the bottom visible page of the document:
//Scroll to the bottom of the browser
function scrollToBottom(){
    //Get the height of the document and viewport
    var documentHeight = document.documentElement.offsetHeight;
    var viewportHeight = window.innerHeight ; //or use the getViewPortSize() method above

    //then, scroll to make the last page visible in the viewport
    window.scrollTo(0, documentHeight - viewportHeight);
}
Copy code
Window's scrollBy method is similar to scroll() and scrollTo(), but its parameters are relative and increase on the offset of the current scroll bar. For example, quick readers might like this:
javascript:void setInterval(function(){scrollBy(0, 10)}, 200)
;
position, and convert it to document coordinates, and then use the scrollTo() method to achieve the purpose. But it is more convenient to call the scrollIntoView() method on the Html element that needs to be displayed.

  The behavior of scrollIntoView() is similar to the browser-generated behavior after setting window.location.hash to the name of a named anchor.


  Element Size, Position, and Overflow The read-only offsetWidth and offsetHeight properties of


  any HTML element return its screen size in CSS pixels. The returned dimensions include the element's borders and padding, with margins removed.

  All HTML elements have offsetLeft and offsetTop properties that return the element's X and Y coordinates. These values ​​are document coordinates and directly specify the position of the element. For descendants of a positioned element and some other elements, the coordinates returned by these properties are relative to the ancestor element rather than the document.

  The offsetParent property specifies the parent element to which these properties are relative. If offsetParent is null, these properties are document coordinates, so in general, using offsetLeft and offsetTop to calculate the position of element e requires a loop:
//Calculate element position
function getElementPosition(e){
    var x = 0, y = 0;
    while(e != null){
        x += e.offsetLeft;
        y += e.offsetTop; e
        = e.offsetParent; }
    return

    {x: x, y: y };
} is to calculate the correct value, let's see how to fix it. In addition to these attributes whose names begin with offset, all document elements define two other sets of attributes, one with names starting with client and the other with scroll. That is, each element has these properties: I ask .png In order to understand the client and scroll properties, you need to know that the actual content of the element may be larger than the box it was allocated to hold, so a single element may have scroll bars. The content area is the viewport, just like the browser window. When the actual content is larger than the viewport, the scroll position of the element needs to be taken into account.





  clientWidth and clientHeight are similar to offsetWidth and offsetHeight, except that they do not include border size. Contains only content and padding. Also, if the browser adds a scrollbar between the padding and the border, clientWidth and clientHeight do not include the scrollbar dimensions. When these properties are queried on the document's root element, their return values ​​are equal to the window's innerWidth and innerHeight properties.

  The clientLeft and clientTop properties are of little use: they return the horizontal and vertical distance between the outer border of the element's padding and the outer edge of its border.

  scrollWidth and scrollHeight are the dimensions of the element's content area plus its padding plus any overflowing content. These properties are equal to clientWidth and clientHeight when the content exactly matches the content area without overflowing. When there is overflow, the overflow content size is included.

  scollLeft and scrollTop specify the position of the element's scroll bar. They were queried in the getScrollOffsets() method. Note that scrollLeft and scrollTop are writable, by setting them to scroll the content in the element (HTML elements do not have a scrollTo() method similar to the Window object.


  DEMO


  The following code introduces the use of the previous functions:
<!DOCTYPE html >
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <
            // Put back the position of the scroll bar with the x and y properties of an object
            function getScrollOffsets(w){
                w = w || window;
                // All browsers except IE 8 and earlier support
                if(w. pageXOffset != null) return {x: w.pageXOffset, y: w.pageYOffset};
                //For IE in standard mode
                var d = w.document;
                if(document.compatMode == "CSS1Compat")
                    return {x: d.documentElement.scrollLeft, y: d.documentElement.scrollTop};
                //return to the browser in crown mode
                { x: d.body.scrollLeft, y: d.body.scrollTop};
            }

            //as an object The w and h properties return the size of the viewport
            function getViewportSize(w){
                //Use the specified window, if there is no parameter, use the current window
                w = w || window;

                //Except IE8 and earlier versions, other browsers can use
                if(w.innerWidth != null)
                    return { w: w.innerWidth, h: w.innerHeight};

                //For IE in standard mode (or any browser)
                var d = w.document;
                if(document.compatMode == "CSS1Compat")
                    return {w: d .documentElement.clientWidth, h: d.documentElement.clientHeight};

                //return to browsers in weird mode
                {w: d.body.clientWidth, h: d.body.clientHeight};
            }

            //element relative to the document Coordinate position
            function getElementRect(e){
                var box = e.getBoundingClientRect();
                var offsets = getScrollOffsets();
                var x = box.left + offsets.x;
                var y = box.top + offsets.y;

                return {x:x, y: y};
            }

            //Element size
            function getElementSize(e){
                var box = getElementRect(e);
                var w = box.width || box.right - box.left;
                var h = box.height || box.bottom - box.top;

                return {w: w, h: h};
            }

            //Scroll to the bottom of the browser
            function scrollToBottom(){
                //Get the height of the document and viewport
                var documentHeight = document.documentElement.offsetHeight;
                var viewportHeight = window.innerHeight; //or use the getViewPortSize() method above

                //then, scroll to make the last page visible in the viewport
                window.scrollTo(0, documentHeight - viewportHeight);
            }

            //Calculate element position
            function getElementPosition(e){
                var x = 0, y = 0;
                while(e != null){
                    x += e.offsetLeft;
                    y += e.offsetTop;
                    e = e.offsetParent;
                }

            return {x: x, y: y };
            }
        </script>
    </head>
    <body>
        <button id="scrolltoBottomBtn">scroll to browser</button>
        <div style="height: 400px; background: red;">

        </div>
        <button id="btn"> Get scrollbar position</button>
        <button id="viewportBtn">Get viewport size</button>
        <button id="eleRectBtn">Element document coordinates</button>
        <script type="text/javascript">
            var btn = document.getElementById("btn");
            btn.onclick = function(event){
            console.log(getScrollOffsets());
            }

            var viewportBtn = document.getElementById(" viewportBtn");
            viewportBtn.onclick = function(event){
            console.log(getViewportSize());
            }

            var eleRectBtn = document.getElementById("eleRectBtn");
            eleRectBtn.onclick = function(eevent){
            console.log(getElementRect(this));
            }

            var scrolltoBottomBtn = document.getElementById("scrolltoBottomBtn");
            scrolltoBottomBtn.onclick = function(){
            scrollToBottom();
            }
        </script>
    </body>
</html>

转自解放号社区:http://bbs.jointforce.com/topic/26095

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326848772&siteId=291194637