Get DOM element position and size

Source: Internet
Author: User

JavaScript gets DOM element position and size

In some complex pages, we often use JavaScript to deal with some of the dynamic effects of DOM elements, which is often used to calculate the location and size of some elements, the browser compatibility problem is not negligible, to write the desired effect of the JavaScript code, We need to know some basic knowledge.

Basic concepts

To facilitate understanding, we need to understand several basic concepts, each with 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 there may be scrollbars, the content area is the viewport, and when the actual content is larger than the viewport, the element's scroll bar position needs to be taken into account.

1. ClientHeight and clientwidth are used to describe the dimensions within the element, which refers to the element content + padding size, excluding the border (actually included under IE ), margin, scroll bar part

2. Offsetheight and offsetwidth are used to describe the outer dimensions of an element, which refers to the element content + padding + border, excluding margins and scroll bar parts

3. ClientTop and ClientLeft return the horizontal and vertical distance between the edge of the inner margin and the outer edge of the bounding rectangle, that is, left, top border width

4. offsettop and offsetleft indicate the distance from the upper-left corner of the element (the outer edge of the border) to the top-left corner of the positioned parent container (offsetparent object)

5. The Offsetparent object refers to the element's nearest position (Relative,absolute) ancestor, which returns null if no ancestor element is positioned.

Write a small example to facilitate understanding

<DivID= "Divparent"style= "padding:8px; Background-color: #aaa; position:relative;">        <DivID= "Divdisplay"style= "Background-color: #0f0; margin:30px; padding:10px; height:200px; width:200px; Border:solid 3px #f00; ">        </Div>    </Div>
<script type= "Text/javascript" >vardiv = document.getElementById (' Divdisplay '); varClientHeight =Div.clientheight; varClientWidth =Div.clientwidth; Div.innerhtml+ = ' clientheight: ' + clientheight + ' <br/> '; Div.innerhtml+ = ' clientwidth: ' + clientwidth + ' <br/> '; varClientLeft =Div.clientleft; varClientTop =Div.clienttop; Div.innerhtml+ = ' clientleft: ' + clientleft + ' <br/> '; Div.innerhtml+ = ' clienttop: ' + clienttop + ' <br/> '; varOffsetheight =Div.offsetheight; varOffsetwidth =Div.offsetwidth; Div.innerhtml+ = ' offsetheight: ' + offsetheight + ' <br/> '; Div.innerhtml+ = ' offsetwidth: ' + offsetwidth + ' <br/> '; varOffsetleft =Div.offsetleft; varOffsetTop =Div.offsettop; Div.innerhtml+ = ' offsetleft: ' + offsetleft + ' <br/> '; Div.innerhtml+ = ' OffsetTop: ' + offsetTop + ' <br/> '; varOffsetParent =div.offsetparent; Div.innerhtml+ = ' offsetParent: ' + offsetparent.id + ' <br/> '; </script>

Effect

We can see that clientheight is the height of div + 10px padding,clientwidth

and ClientLeft and ClientTop are div left, top border width

Offsetheight is clientheight+ the sum of the width of the upper and lower 3px borders, offsetwidth the same

offsettop is div 30px maggin+offsetparent 8px padding,offsetleft the same

6. ScrollWidth and ScrollHeight are the content area of the element plus the padding plus the overflow dimension, which is equal to clientwidth and clientheight when the content is exactly the same as the content area without overflow

7. ScrollLeft and ScrollTop refer to the position of the element scroll bars , which are writable

Let's write a simple example to understand

<DivID= "Divparent"style= "Background-color: #aaa; padding:8px; border:solid 7px #000; height:200px; width:500px; overflow:auto;">        <DivID= "Divdisplay"style= "Background-color: #0f0; margin:30px; padding:10px; height:400px; width:200px; Border:solid 3px #f00; ">        </Div>    </Div>
 <script type= "Text/javascript" > var  DIVP = document.getElementById (        ' Divparent ' );  var  DIVD = document.getElementById (' Divdisplay '        );         var  scrollheight = Divp.scrollheight;         var  scrollwidth = Divp.scrollwidth;        divd.innerhtml  + = ' scrollheight: ' + scrollheight + ' <br/> ' 

In Firefox and IE10 (IE10 the following version of the box model and the standards are not consistent, no discussion, compatibility issues will be described below) to get results scrollheight: 494, And in Chrome and Safari to get results scrollheight: 502, poor 8px, according to 8 can be simple speculation is divparent padding, to calculate is not

We can see how their results come from, first of all scrollheight must contain the height of divdisplay required 400px height + 10px padding+ up and down each 3px border+ up and down each 30px margin, so

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

So 486+8=494, 486+8*2=502 really is so, in Firefox and IE10 under no calculation under padding

With these basics in place, we can calculate the position and size of the elements.

Coordinates relative to the document and viewport

When we calculate the location of a DOM element, which is the coordinate, it involves two coordinate systems, document coordinates and viewport coordinates .

The document we often use is the entire page part, not just the visible part of the window, but also the part of the scroll bar that appears because of the window size limit, which is what we call the origin of the document coordinates.

Viewports are part of the browser that displays the contents of a document, which does not include the browser shell (menu, toolbar, status bar, etc.), that is, the current window displays the page portion, excluding the scroll bar.

If the document is smaller than the viewport, the description does not appear to scroll, the upper-left corner of the document is the same as the upper-left corner of the viewport, and generally toggles between the two coordinate systems, with or minus the scrolling offset (scroll offset).

In order to convert between coordinate systems, we need to determine the scroll bar position of the browser window. The Pagexoffset and pageYOffset of the window object provide these values, with the exception of IE 8 and earlier versions. Scroll bar positions can also be obtained through the scrollleft and ScrollTop properties, which , under normal circumstances, are obtained by querying the document root node (document.documentelement), but must be queried through the body of the document in weird mode .

functionGetscrolloffsets (w) {varw = W | |window; if(W.pagexoffset! =NULL) {                return{x:w.pagexoffset, y:pageyoffset}; }            varD =w.document; if(Document.compatmode = = "Css1compat")                return{x:d.documentelement.scrollleft, y:d.documentelement.scrolltop}; return{x:d.body.scrollleft, y:d.body.scrolltop}; }

Sometimes it's very useful to judge the size of the viewport.

functionGetviewportsize (w) {varw = W | |window; if(W.innerwidth! =NULL)                return{w:w.innerwidth, h:w.innerheight}; varD =w.document; if(Document.compatmode = = "Css1compat")                return{w:d.documentelement.clientwidth, h:d.documentelement.clientheight}; return{w:d.body.clientwidth, h:d.body.clientheight}; }

Document coordinates

Any HTML element has Offectleft and Offecttop properties that return the x and y coordinates of the element, and for many elements, these values are document coordinates, but for the positioning of the element descendants and some other elements (table cells), the coordinates relative to the ancestor are returned. We can calculate by simple recursive upstream summation

function Getelementposition (e) {            var x = 0, y = 0;              while NULL ) {                + = e.offsetleft                ; + = e.offsettop                ; = e.offsetparent;            }             return {x:x, y:y};        }

However, this function does not always calculate the correct value, and when the document contains scrollbars, this method does not work properly, we can only use this method without a scrollbar, but we use this principle to calculate the coordinates of some elements relative to a parent element.

Viewport coordinates

The calculation of viewport coordinates is relatively straightforward and can be done by invoking the Getboundingclientrect method of the element . The bottom method returns an object with a left, right, top, and a property that represents the coordinates of the four positions of the element relative to a viewport. The coordinates returned by getboundingclientrect contain the inner margins and borders of the elements, and do not contain margins. Compatibility is very good, very useful

Element size

By calculating the coordinate method above, we can easily derive the element size. The objects returned in the Getboundingclientrect browser include width and height, but are not implemented in the original IE, but can be easily computed by returning the Right-left and Bottom-top of the object.

Original: http://www.cnblogs.com/dolphinX/archive/2012/11/19/2777756.html

Get DOM element position and size

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.