search
HomeWeb Front-endJS TutorialHow to get the position and size of DOM elements using JavaScript_Basic knowledge

在一些复杂的页面中经常会用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: var div = document.getElementById('divDisplay');
var clientHeight = div.clientHeight;
var clientWidth = div.clientWidth;
div.innerHTML = 'clientHeight: ' clientHeight '
';
div.innerHTML = 'client Width : ' clientWidth '
';

var clientleft = div.ClientLeft;
var clienttop = div.clienttop;
DIV.Innerhtml = 'Clientleft' & lt; br/& gt; '; Iv.innerhtml = 'Clienttop : ' clientTop '
';

var offsetHeight = div.offsetHeight;

var offsetWidth = div.offsetWidth;
div.innerHTML = 'offsetHeight: ' offsetHeight '
';
div.innerHTML = 'offset Width : ' offsetWidth '
';

var OffsetLeft = div.offsetLeft;

var officialtop = div.Offsettop;
Div.Innerhtml = 'OffSetleft' & LT; br/& gt; ' ; DIV.Innerhtml = 'Offsettop : ' offsetTop '
';

var offsetParent = div.offsetParent;

div.innerHTML = 'offsetParent: ' offsetParent.id '
';




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.
Statement
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version