Home Web Front-end JS Tutorial How 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
javascript Location element

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
}
Copy after login

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
Copy after login

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
Copy after login

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 http-equiv="x-ua-compatible" content="ie=edge"/>
Copy after login

.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, …}
Copy after login

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)
Copy after login

.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!'
Copy after login

兼容性和限制:.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 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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Location of Origami Bird at Stardome Railway Crocker Film and Television Park Location of Origami Bird at Stardome Railway Crocker Film and Television Park Mar 27, 2024 pm 11:51 PM

There are a total of 20 origami birds in Croaker Film and Television Park on Star Dome Railway. Many players don’t know where the origami birds are in Crocker Film and Television Park. The editor has summarized the locations of each origami bird to help everyone. Search for it, and take a look at this latest summary of the locations of the origami birds in Croaker Film and Television Park for specific content. Guide to the Honkai Star Dome Railway: Origami Bird in Crook Movie Park Location 1, Crook Movie Park 1st Floor 2, and Crook Movie Park 2nd Floor Star Dome Railway

Understand the location and structure of pip installation package storage Understand the location and structure of pip installation package storage Jan 18, 2024 am 08:23 AM

To learn more about the storage location of packages installed by pip, you need specific code examples. Pip is a commonly used package management tool in the Python language. It is used to easily install, upgrade and manage Python packages. When using pip to install a package, it will automatically download the corresponding package file from PyPI (Python Package Index) and install it to the specified location. So, where are the packages installed by pip stored? This is a problem that many Python developers will encounter. This article will delve into the location of the packages installed by pip and provide

win11 shutdown location win11 shutdown location Jan 10, 2024 am 09:14 AM

If we are going to be away from the computer for a long time, it is best to shut down the computer to protect it. So where is the shutdown in win11? In fact, generally speaking, just open the start menu and you can find the shutdown button in it. Where to shut down Windows 11: Answer: In the power button of the start menu. 1. First, we click the "Windows Logo" on the bottom taskbar to open the "Start Menu" 2. After opening, you can find the "Power" button in the lower right corner, as shown in the figure. 3. After clicking the power button, you will see "Shutdown", click it to shut down. 4. If the computer cannot be shut down due to special circumstances such as a crash, you can directly press and hold the "power button" on the computer to force a shutdown.

Where is the Last Era Arena? Where is the Last Era Arena? Mar 07, 2024 pm 08:16 PM

In "Last Age", players can play in various modes such as game mode, challenge mode, and arena, etc. Arena is the ultimate way to play the game, providing two modes for players to choose from. Where is the Arena in the Last Era? Answer: The Arena is an endgame game, and its specific location is at the Champion's Gate. You need to obtain the Arena Key or Memory Arena Key. After right-clicking, you can see the world map and find the specific location of the Champion's Gate. The arena is divided into two major modes: Arena Championship Mode and Endless Arena Mode. The former includes 40 waves of enemies and selected rewards, always culminating in a battle with the Arena Champion. There are 4 stages in Arena Championship Mode. The higher the difficulty, the better the rewards. Endless Arena is a mode with infinite waves. The difficulty gradually increases. The challenger with the best score will

Where is Kuaishou published and how to change its location? How to add a location to a video that has been uploaded? Where is Kuaishou published and how to change its location? How to add a location to a video that has been uploaded? Mar 21, 2024 pm 06:00 PM

As a well-known short video platform in China, Kuaishou provides many creators with opportunities to showcase their talents and share their lives. When uploading a video, some novice creators may be confused about how to change the video posting location. This article will introduce you to how to change the publishing location of Kuaishou videos, and share some tips for Kuaishou video publishing to help you make better use of this platform to showcase your work. 1. Where is Kuaishou published and how to change its location? 1. Publishing interface: In Kuaishou APP, click the &quot;Publish&quot; button to enter the video publishing interface. 2. Location information: In the publishing interface, there is a &quot;Location&quot; column. Click to enter the location selection interface. 3. Change location: In the location selection interface, click the &quot;Location&quot; button to view the current location. If you want to change the location, click &quot;Location&quot;

Where is the Meituan Daily Voucher location_Meituan Daily Voucher location introduction Where is the Meituan Daily Voucher location_Meituan Daily Voucher location introduction Mar 27, 2024 pm 05:11 PM

1. We open Meituan on the mobile phone, and then click on the takeout option in the upper left corner of the homepage. 2. After entering the takeout platform page, you can see the section with daily coupons on the homepage, click on it directly. 3. After entering the Tiantian God Voucher, you will see a lot of activities, click Finish, and then we can get rewards after completing the tasks.

How to change the location of Gaode Map Home How to change the location of Gaode Map Home Feb 27, 2024 pm 07:31 PM

As a powerful assistant for our daily travels, Amap not only provides accurate navigation services, but also allows users to directly determine their "home location" in a user-friendly manner. It is convenient to check your route home every time. But sometimes the location of our home also needs to be updated, so how can we easily modify the "location of home" in Amap? Next, follow the editor's guide and learn how to modify it together! Amap How to change the location of your home? Answer: [AMAP] - [Settings] - [Three-dot icon] - [Modify location] - [Set location] - [Set as home address]. Specific steps: 1. First open the Amap software, enter the homepage, slide up, find home and click [Settings]; 2. Then in the settings page, we can

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles