How to use JavaScript to obtain the DOM element position and size

Source: Internet
Author: User

In some complex pages, JavaScript is often used to process the dynamic effects of some DOM elements. In this case, we often use the calculation of the position and size of some elements. The browser compatibility issue is also an important part, to write JavaScript code with expected results, we need to know some basic knowledge.

Basic Concepts

To facilitate understanding, we need to understand several basic concepts. Each HTML element has the following attributes:

OffsetWidth

ClientWidth

ScrollWidth

OffsetHeight

ClientHeight

ScrollHeight

OffsetLeft

ClientLeft

ScrollLeft

OffsetTop

ClientTop

ScrollTop


To understand these attributes, we need to know that the actual content of the HTML element may be larger than the box allocated to hold the content, so the scroll bar may appear, and the content area is the viewport, when the actual content is larger than that of the viewport, the position of the element's scroll bar needs to be taken into account.

1. clientHeight and clientWidth are used to describe the inner size of an element. They are the content of an element + the size of the inner margin, excluding the border (actually included under IE), the outer margin, and the scroll bar.

2. offsetHeight and offsetWidth are used to describe the outer size of an element. They refer to the element content, padding, and border, excluding the outer margin and the scroll bar.

3. clientTop and clientLeft return the horizontal and vertical distance between the edge of the inner margin and the outer edge of the border, that is, the left and top Border width.

4. offsetTop and offsetLeft indicate the distance between the upper left corner (outer border edge) of the element and the upper left corner of the located parent container (offsetParent object ).

5. The offsetParent object refers to the relative (absolute) ancestor element of the element. It is recursively traced. If no ancestor element is located, null is returned.

Write a small example for ease of understanding
Copy codeThe Code is as follows:
<Div id = "divParent" style = "padding: 8px; background-color: # aaa; position: relative;">
<Div id = "divDisplay" style = "background-color: #0f0; margin: 30px; padding: 10px;
Height: 200px; width: 200px; border: solid 3px # f00; ">
</Div>
</Div>

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var div = document. getElementById ('divdisplay ');

Var clientHeight = div. clientHeight;
Var clientWidth = div. clientWidth;
Div. innerHTML + = 'clientheight: '+ clientHeight +' <br/> ';
Div. innerHTML + = 'clientwidth: '+ clientWidth +' <br/> ';

Var clientLeft = div. clientLeft;
Var clientTop = div. clientTop;
Div. innerHTML + = 'clientleft: '+ clientLeft +' <br/> ';
Div. innerHTML + = 'clienttop: '+ clientTop +' <br/> ';

Var offsetHeight = div. offsetHeight;
Var offsetWidth = div. offsetWidth;
Div. innerHTML + = 'offsetheight: '+ offsetHeight +' <br/> ';
Div. innerHTML + = 'offsetwidth: '+ offsetWidth +' <br/> ';

Var offsetLeft = div. offsetLeft;
Var offsetTop = div. offsetTop;
Div. innerHTML + = 'offsetleft: '+ offsetLeft +' <br/> ';
Div. innerHTML + = 'offsettop: '+ offsetTop +' <br/> ';

Var offsetParent = div. offsetParent;
Div. innerHTML + = 'offsetparent: '+ offsetParent. id +' <br/> ';
</Script>

Effect

We can see that clientHeight is the height of the div + the padding of up and down 10px, and the same is true for clientWidth.

ClientLeft and ClientTop are the left and top Border width of the div.

OffsetHeight is the sum of the Border Width of clientHeight + the upper and lower 3px, and the same is true for offsetWidth.

OffsetTop is the padding of maggin + offsetparent 8px of div 30px. The same applies to offsetLeft.

 

6. scrollWidth and scrollHeight are the content area of the element plus the padding plus the overflow size. When the content exactly matches the content area without Overflow, these attributes are equal to clientWidth and clientHeight.

7. scrollLeft and scrollTop refer to the position of the element's scroll bar. They are writable.

The following is a simple example.

Copy codeThe Code is as follows:
<Div id = "divParent" style = "background-color: # aaa; padding: 8px; border: solid 7px #000; height: 200px; width: 500px; overflow: auto; ">
<Div id = "divDisplay" style = "background-color: #0f0; margin: 30px; padding: 10px;
Height: 400px; width: 200px; border: solid 3px # f00; ">
</Div>
</Div>

Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var divP = document. getElementById ('divparent ');
Var divD = document. getElementById ('divdisplay ');

Var scrollHeight = divP. scrollHeight;
Var scrollWidth = divP. scrollWidth;
DivD. innerHTML + = 'rollheight: '+ scrollHeight +' <br/> ';
DivD. innerHTML + = 'rollwidth: '+ scrollWidth +' <br/> ';
</Script>

The result scrollHeight: 494 is displayed in FireFox and IE10 (the Box Model of IE10 or earlier versions is inconsistent with the W3C standard and is not discussed. The compatibility problem is described below, in Chrome and Safari, The result scrollHeight is 502, with an error of 8 PX. According to 8, we can simply guess that it is the padding of divParent.

We can see how they come from, first, scrollHeight must contain the PX height required by divDisplay, The 10px padding for each top and bottom, and the border for each 3px for each top and bottom, and the margin for 30 PX for each top and bottom.

400 + 10*2 + 3*2 + 30*2 = 486

In this case, 486 + 8 = 494,486 + 8*2 = 502,Padding is not calculated in FireFox and IE10.

With this basic knowledge, we can calculate the position and size of elements.

Coordinates relative to the document and the viewport

When we calculate a DOM element location, that is, the coordinates, two coordinate systems are involved, the coordinate system of the document and the coordinate system of the view.

The document we often use is the entire page, not only the visible part of the window, but also the part where the scroll bar appears due to the limited size of the window, the upper-left corner of the origin is what we call the origin point relative to the coordinate of the document.

The view is a part of the browser that displays document content. It does not include the browser shell (menu, toolbar, status bar, etc.), that is, the page section of the current window, but not the scroll bar.

If the document is smaller than the viewport, it means that there is no scroll. the upper left corner of the document is the same as the upper left corner of the viewport. Generally, you need to add or subtract the scroll offset between the two coordinate systems ).

In order to convert the coordinates, we need to determine the position of the browser window scroll bar. The pageXoffset and pageYoffset values of the window object are provided, except for IE 8 and earlier versions. You can also obtain these attribute values through scrollleftand scrolltopreferers in normal situations and by querying the document root node (document.doc umentElement). However, in weird mode, you must query these attribute values through the document body.

Copy codeThe Code is as follows:
Function getscroloffsets (w ){
Var w = w | window;
If (w. pageXoffset! = Null ){
Return {x: w. pageXoffset, y: pageYoffset };
}
Var d = upload Doc ument;
If (document. compatMode = "CSS1Compat ")
Return {x: d.doc umentElement. scrollLeft, y: d.doc umentElement. scrollTop };
Return {x: d. body. scrollLeft, y: d. body. scrollTop };
}

Sometimes it is very useful to determine the size of the view.

Copy codeThe Code is as follows:
Function getViewPortSize (w ){
Var w = w | window;
If (w. innerWidth! = Null)
Return {w: w. innerWidth, h: w. innerHeight };
Var d = upload Doc ument;
If (document. compatMode = "CSS1Compat ")
Return {w: d.doc umentElement. clientWidth, h: d.doc umentElement. clientHeight };
Return {w: d. body. clientWidth, h: d. body. clientHeight };
}

Document coordinates

Any HTML element has the offectLeft and offectTop attributes to return the X and Y coordinates of the element. For many elements, these values are the coordinates of the document, however, for positioning element descendants and some other elements (Table units), the coordinates relative to the ancestor are returned. We can use simple recursive incremental Calculation

Copy codeThe Code is as follows:
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 };
}

Even so, this function does not always calculate the correct value. When the document contains a scroll bar, this method cannot work normally. We can only use this method without a scroll bar, however, we use this principle to calculate the coordinates of some elements relative to a parent element.

View Coordinate

It is much easier to calculate the coordinates of the view. You can call the getBoundingClientRect method of the element. Returns an object with the left, right, top, and bottom attributes, representing the coordinates of the elements at the four positions relative to the view. The coordinates returned by getBoundingClientRect contain the element's padding and border, excluding the margin. Good compatibility, very easy to use

Element size

By calculating the coordinates above, we can easily obtain the element size. The objects returned by getBoundingClientRect In the W3C-compliant browser also include width and height, but are not implemented in the original IE. However, the right-left and bottom-top of the returned object can be conveniently calculated.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.