Home > Web Front-end > JS Tutorial > body text

How to get the position and size of DOM elements using JavaScript_Basic knowledge

WBOY
Release: 2016-05-16 17:37:24
Original
1625 people have browsed it

在一些复杂的页面中经常会用JavaScript处理一些DOM元素的动态效果,这种时候我们经常会用到一些元素位置和尺寸的计算,浏览器兼容性问题也是不可忽略的一部分,要想写出预想效果的JavaScript代码,我们需要了解一些基本知识。

基础概念

为了方便理解,我们需要了解几个基础概念,每个HTML元素都有下列属性

offsetWidth

clientWidth

scrollWidth

offsetHeight

clientHeight

scrollHeight

offsetLeft

clientLeft

scrollLeft

offsetTop

clientTop

scrollTop


In order to understand these properties, we need to know that the actual content of the HTML element may be larger than the box allocated to accommodate the content, so scroll bars may appear. The content area is the viewport. When the actual content is larger than the viewport When doing this, you need to take the scroll bar position of the element into consideration.

1. clientHeight and clientWidth are used to describe the inner size of the element, which refers to the size of the element content, inner margin, excluding the border (actually included in IE), margins, and scroll bar parts

2. offsetHeight and offsetWidth are used to describe the outer size of the element, which refers to the element content, inner margin, and border, excluding the outer margin and scroll bar part

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

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

5. The offsetParent object refers to the most recently positioned (relative, absolute) ancestor element of the element, recursively tracing back, if no ancestor element is positioned, null will be returned

Write a small example to facilitate understanding

Copy the code The code is as follows:


         
The code is as follows:


The effect is as shown in the picture

We can see from the picture that clientHeight is the height of the div with 10px padding on the top and bottom. The same is true for clientWidth

And clientLeft and ClientTop are the width of the left and top borders of the div

offsetHeight is the sum of the 3px border widths above and below clientHeight. The same is true for offsetWidth

offsetTop is div 30px maggin offsetparent 8px padding, offsetLeft is the same

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

7. scrollLeft and scrollTop refer to the position of the scroll bar of the element, and they are writable

Write a simple example below to understand

Copy code The code is as follows:


  

>





In FireFox and IE10 (versions below IE10, the box model is inconsistent with the W3C standard, without discussion, compatibility The problem will be introduced below) and the result scrollHeight: 494 is obtained, while the result scrollHeight: 502 is obtained under Chrome and Safari, which is a difference of 8px. Based on 8, we can simply guess that it is the padding of divParent. Let’s calculate whether it is


We can see how their results come from. First of all, scrollHeight must contain the height required by divDisplay, a height of 400px, a padding of 10px above and below, a border of 3px above and below, and a margin of 30px above and below, so

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

In this way, 486 8=494, 486 8*2=502 is indeed the case.

Padding is not calculated in FireFox and IE10

With these basic knowledge in hand, we can calculate the position and size of elements.

Coordinates relative to the document and viewport

When we calculate the position of a DOM element, which is the coordinates, two coordinate systems are involved, 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 where the scroll bar appears due to the window size limit. Its upper left corner is what we call the origin relative to the document coordinates.

The viewport is the part of the browser that displays the document content. It does not include the browser shell (menu, toolbar, status bar, etc.), that is, the part of the page displayed in the current window, excluding scroll bars.

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

In order to convert between coordinate systems, we need to determine the scroll bar position of the browser window. These values ​​are provided by the window object's pageXoffset and pageYoffset, except in IE 8 and earlier. The scroll bar position can also be obtained through the scrollLeft and scrollTop attributes. Under normal circumstances, these attribute values ​​​​can be obtained by querying the document root node (document.documentElement), but in weird mode, it must be queried through the body of the document.

Copy code The code is as follows:

function getScrollOffsets(w) {
            var w = w || window; ; Left, y: d.documentElement.scrollTop };
                                                                                                                                                  🎜>




Copy code


The code is as follows:

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 offectLeft and offectTop attributes that return the X and Y coordinates of the element. For many elements, these values ​​​​are document coordinates, but for positioned descendants of the element and some other elements (table cells), returns are relative to the ancestor. coordinate. We can calculate it through simple recursion and accumulation




Copy code
The code is as follows:

function getElementPosition(e) {

var x = 0, y = 0;

while (e != null) { x = e.offsetLeft; y = e, offsetTop; e = e.offsetPar ent; }                  return { x: It doesn't work properly. We can only use this method without scroll bars, but we use this principle to calculate the coordinates of some elements relative to a parent element.
Viewport coordinates


Calculating the viewport coordinates is relatively simple. You can call the element's getBoundingClientRect method. The method returns an object with left, right, top, and bottom attributes, which respectively represent the coordinates of the element's four positions relative to the viewport. The coordinates returned by getBoundingClientRect include the element's padding and border, but do not include the outer margin. Very compatible and very easy to use


Element size


From the above method of calculating coordinates, we can easily obtain the element size. In browsers that comply with W3C standards, the objects returned by getBoundingClientRect also include width and height, but they are not implemented in the original IE, but they can be easily calculated by returning the right-left and bottom-top of the object.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!