search
HomeWeb Front-endJS TutorialHow to get the position of DOM elements in JS

How to get the position of DOM elements in JS

Apr 27, 2018 am 10:50 AM
javascriptLocationelement

This time I will show you how to obtain the position of DOM elements in JS. What are the precautions for obtaining the position of DOM elements in JS? 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:

APIUsageDocumentationStandardoffsetTopThe position of the relative positioning containerMDNCSSOM View ModuleclientTopTop border widthMDNCSSOM View Module.getBoundingClientRect()Element size and position relative to the viewport MDNCSSOM View Module.getClientRects()The size and position of all child CSS boxesMDNCSSOM View Module.getComputedStyle()Apply all style sheets and CSS properties after calculationMDNDOM 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 except the border (PaddingContent 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=getboundingclientrect IE The upper left corner of the window may not be 0,0. In IE9, you can set it to 0,0 like this:

<meta>

.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></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></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!'

兼容性和限制:.getComputedStyle() 几乎兼容所有浏览器,可参考 https://caniuse.com/#search=getComputedStyle。但它返回的值是 CSS 属性,用它获取绝对位置时要注意值的类型。例如 left 可能是 13px 这样的绝对值,也可能是 auto 这样的 CSS 关键字。

总结 获取 DOM 元素相对于文档的位置,可以直接使用 offsetTop; 获取 DOM 元素相对于视口的位置,可以使用 .getBoundingClientRect(); 获取 SVG 元素或行内元素的 CSS 盒子(比如用来做文本高亮时),可以使用 .getClientRects(); 获取绝对定位元素、伪元素的渲染后 CSS 属性,可以使用 .getComputedStyle()

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Angular4性能优化方法总结

jQuery+ajax动态操作表格tr td步骤详解

The above is the detailed content of How to get the position of DOM elements in JS. For more information, please follow other related articles on the PHP Chinese website!

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
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.