JavaScript to get 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, javaScript to write the expected resultsCode, 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, which is the content of an element + the size of the inner margin, excluding the border (In IE), Margin, and 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 upper left corner of the element (borderOuter Edge) AndLocatedDistance in the upper left corner of the parent container (offsetparent object)

5. The offsetparent object refers to the latest elementPositioning(Relative, absolute) the ancestor element is recursively traced. If no ancestor element is located, null is returned.

Write a small example for ease of understanding

 <  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  > 
<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 areWritableOf

The following is a simple example.

 <  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 > 
 
<SCRIPT type = "text/JavaScript">VaRDivp = Document. getelementbyid ('divparent');VaRDivd = Document. getelementbyid ('divdisplay');VaRScrollheight =Divp. scrollheight;VaRScrollwidth =Divp. scrollwidth; divd. innerhtml+ = 'Rollheight: '+ scrollheight +' <br/>'; Divd. innerhtml+ = 'Rollwidth: '+ scrollwidth +' <br/>';</SCRIPT>

The result scrollheight is displayed in Firefox and ie10 (the Box Model of ie10 or earlier versions is inconsistent with W3C standards and is not discussed. The compatibility issue is described below:494In Chrome and Safari, The result scrollheight is as follows:502, Bad8pxAccording to 8, we can simply guess that it is the padding of divparent to calculate whether it is

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, coordinates, two coordinate systems are involved,Document coordinatesAndView Coordinate.

We often useDocument is the entire page, not just the visible part of the window.It also includes the scroll bar section due to the size limit of the window. The upper left corner of the scroll bar is the so-called origin point relative to the coordinate of the document.

The viewport is part of a browser that displays document content. It does not include a browser shell.(Menu, toolbar, status bar, etc.), that is, the page section displayed in the current window, excluding 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 the position of the scroll bar through the scrollleft and scrolltop attributes,In normal situations, you can obtain these attribute values through querying the document root node (document.doc umentelement). However, in weird mode, you must query these attribute values through the document body..

 Function  Getscroloffsets (w ){  VaR W = w | Window;  If (W. pagexoffset! = Null  ){  Return {X: W. pagexoffset, Y: pageyoffset };}  VaR D = W.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.

 Function  Getviewportsize (w ){ VaR W = w | Window;  If (W. innerwidth! = Null  )  Return  {W: W. innerwidth, H: W. innerheight };  VaR D = W.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 the element to locate its descendant and some other elements (table cells ),Ancestor. We can use simple recursive incremental Calculation

FunctionGetelementposition (e ){VaRX = 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

ComputingView CoordinateIt is much simpler. You can callElementOfGetboundingclientrectMethod. 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., Does not contain the outer 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.

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.