JavaScript to get the DOM element position and size

Source: Internet
Author: User

JavaScript to get the DOM element position and size

First, big graph town building ~

 

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

  
<script type="text/javascript">        var div = document.getElementById('divDisplay');        var clientHeight = div.clientHeight;        var clientWidth = div.clientWidth;        div.innerHTML += 'clientHeight: ' + clientHeight + '
'; div.innerHTML += 'clientWidth: ' + clientWidth + '
'; var clientLeft = div.clientLeft; var clientTop = div.clientTop; div.innerHTML += 'clientLeft: ' + clientLeft + '
'; div.innerHTML += 'clientTop: ' + clientTop + '
'; var offsetHeight = div.offsetHeight; var offsetWidth = div.offsetWidth; div.innerHTML += 'offsetHeight: ' + offsetHeight + '
'; div.innerHTML += 'offsetWidth: ' + offsetWidth + '
'; var offsetLeft = div.offsetLeft; var offsetTop = div.offsetTop; div.innerHTML += 'offsetLeft: ' + offsetLeft + '
'; div.innerHTML += 'offsetTop: ' + offsetTop + '
'; var offsetParent = div.offsetParent; div.innerHTML += 'offsetParent: ' + offsetParent.id + '
'; </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.

  
<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 + '
'; divD.innerHTML += 'scrollWidth: ' + scrollWidth + '
'; </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:502The difference is 8 PX. According to 8, we can simply speculate 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 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.

function getScrollOffsets(w) {            var w = w || window;            if (w.pageXoffset != null) {                return { x: w.pageXoffset, y: pageYoffset };            }            var d = 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 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.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 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

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

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.

There are 3*4 and 12 attributes in total.

The following is an excerpt from Baidu:

First of all, it is useless to tangle with these theories, and the actual operation is not so complicated.
Answer your questions one by one:
1. How is div. clientleft as big as div. style. border?
First, you must understand what clientleft means. To understand clientleft, you must first understand offsetleft. offsetleft refers to this label (or object ), distance from the leftmost end of his parent tag to the leftmost end of his parent tag.
The difference between clientleft and offsetleft is that clientleft = offsetleft minus the border Value of the object.
Therefore, clientleft is as big as border.

2. What is div. style. margin?
Margin refers to the outer margin of the object, which is often used together with padding. The difference is that padding is contained in the clientWidth of the object, margin is not included in any clientWidth, offsetWidth, clientHeight, or offsetHeight.

3. What is div. scrolltop?
As the name suggests, scrolltop is the distance from the top of the volume, that is, the number of elements that have been rolled in the vertical direction.

4. What is body. clienttop?

Body. clienttop refers to the offset value of the body minus border. Like the first problem, because there is no offsetleft, its clienttop is the same as that of border.

Finally, you can understand these theories. There is no need to remember that these theories are rarely used in actual web pages.

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.