


How to get the absolute position of DOM elements in the front-end interface
This time I will show you how to get the absolute position of the DOM element in the front-end interface, and what are the precautions on how to get the absolute position of the DOM element in the front-end interface. The following is a practical case, let's take a look.
When operating page scrolling and animation, the absolute position of DOM elements is often obtained, such as the floating navigation on the left side of this article. When the page scrolls to it, it will be rendered into the document flow normally. When the page scrolls beyond Its position will always be suspended on the left.
This article will detail various methods of obtaining the absolute position of DOM elements and the corresponding compatibility. For information on how to obtain the DOM element height and scroll height, please refer to the article Width, Height and Scroll Height of the Viewport.
Overview
These are the documents and standards corresponding to the APIs involved in this article, for reference:
API | Usage | Documentation | Standard |
---|---|---|---|
offsetTop | The position of the relative positioning container | MDN | CSSOM View Module |
clientTop | Top border width | MDN | CSSOM View Module |
.getBoundingClientRect() | Element size and position relative to the viewport | MDN | CSSOM View Module |
.getClientRects() | The size and position of all child CSS boxes | MDN | CSSOM View Module |
.getComputedStyle() | Apply all style sheets and CSS properties after calculation | MDN | DOM Level 2 Style CSSOM |
offsetTop/offsetLeft
HTMLElement.offsetTop is used to get the position of the current element (excluding the top border) relative to the positioning container. That is to say,
If all ancestor elements are statically positioned position:static;
(this is the default situation), offsetTop
represents the height from the top of the document Poor (the top of the document may have rolled out of the viewport, and this height may be greater than the viewport height).
If there is an absolutely positioned ancestor element position:absolute/fixed
, offsetTop
will be relative to this element. Therefore, in order to obtain the height difference relative to the top of the document, you need to call recursively:
function getOffsetTop(el){ return el.offsetParent ? el.offsetTop + getOffsetTop(el.offsetParent) : el.offsetTop }
el.offsetParent
is the positioning container of the current element. If the current element is not absolutely positioned Ancestor node, the value of this attribute is null
.
Compatibility and limitations: This attribute is supported by almost all browsers. Its value is 0 if the element is hidden, but has no effect in IE9.
clientTop/clientLeft
Don’t be misled by the name, Element.clientTop refers to the width of the top border of the current element an integer value. Always equal to the rounded value of the border-top-width
property returned by getComputedStyle()
.
why? In DOM terminology, client always refers to the rendering box excluding the border (padding content size). Offset always refers to the rendering box containing the border (border, padding, content size), and clientTop
is the difference between the two Tops, that is, the border width. For the concept of the box, please refer to: CSS Display attribute and box model
Compatibility and limitations: Same as offsetTop/offsetLeft
.getBoundingClientRect()
Element.getBoundingClientRect() is used to get the size of the element and its position relative to the viewport, and returns a DOMRect object.
> document.querySelector('span').getBoundingClientRect() DOMRect {x: 2.890625, y: 218.890625, width: 1264, height: 110, top: 218.890625, …} bottom: 328.890625 height: 110 left: 2.890625 right: 1266.890625 top: 218.890625 width: 1264 x: 2.890625 y: 218.890625
If you want to obtain the position relative to the upper left corner of the document, you need to add the scroll position to the above top
and left
. The following code comes from MDN and is compatible with almost all browsers:
// For scrollX (((t = document.documentElement) || (t = document.body.parentNode)) && typeof t.scrollLeft == 'number' ? t : document.body).scrollLeft // For scrollY (((t = document.documentElement) || (t = document.body.parentNode)) && typeof t.scrollTop == 'number' ? t : document.body).scrollTop
Compatibility and limitations: It is also a feature of CSSOM View Module, but it is compatible with almost all browsers. Please refer to
https:/ /caniuse.com/#feat=getboundingclientrectThe upper left corner of the window under IE may not be 0,0. In IE9, it can be set to 0,0 like this:
<meta http-equiv="x-ua-compatible" content="ie=edge"/>
.getClientRects()
Element.getClientRects() is used to obtain a collection of DOMRect corresponding to all CSS box models in the DOM element.
If it is a block-level element, there should be only one element in the returned set, which is the size and position of the block. But if it's an inline element (or an element within an SVG), every CSS box within it will be returned. For example, an ordinary <span>
that is wrapped by default:
> document.querySelector('span').getClientRects() DOMRectList {0: DOMRect, 1: DOMRect, 2: DOMRect, length: 5} 0: DOMRect {x: 2.890625, y: 262.890625, width: 1264, height: 22, top: 262.890625, …} 1: DOMRect {x: 2.890625, y: 284.890625, width: 1264, height: 22, top: 284.890625, …} 2: DOMRect {x: 2.890625, y: 306.890625, width: 768, height: 22, top: 306.890625, …}
This <span>
has three lines, and the length of the third line is less than one line. Each line break forms a new CSS box.
Compatibility and limitations: In IE8 and below, IE's unique TextRectangle
object (instead of ClientRect
) will be returned. This object does not have width
and height
properties, and properties cannot be set on it. Reference: https://webplatform.github.io/docs/dom/HTMLElement/getClientRects/
.getComputedStyle()
Window. getComputedStyle() can get all calculated CSS properties of an element. For simple absolutely positioned elements, the position of the element can be obtained through the top
, left
and other attribute values returned by this API. For example:
let btn = document.querySelector('#btn-scroll-up') let {top, left} = getComputedStyle(btn) console.log('top:', top, 'left:', left)
.getComputedStyle()
There is also a useful usage to get style information such as the size and position of pseudo elements:
// 以下代码来自: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle var h3 = document.querySelector('h3'); var result = getComputedStyle(h3, ':after').content; console.log('the generated content is: ', result); // returns ' rocks!'
Compatibility and limitations:.getComputedStyle()
Compatible with almost all browsers, please refer to https://caniuse.com/#search=getComputedStyle. But the value it returns is a CSS property. When using it to obtain the absolute position, you should pay attention to the type of the value. For example, left
may be an absolute value like 13px
, or it may be a CSS keyword like auto
.
Summary To get the position of the DOM element relative to the document, you can directly use offsetTop
; To get the position of the DOM element relative to the viewport, you can use .getBoundingClientRect()
; To get the SVG element Or the CSS box of an inline element (for example, when used for text highlighting), you can use .getClientRects()
; to get the rendered CSS properties of absolutely positioned elements and pseudo elements, you can use .getComputedStyle ()
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
JS try-catch statement and error type usage
How to transfer configuration data from code Center separation
The above is the detailed content of How to get the absolute position of DOM elements in the front-end interface. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...
