


How 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
var clientHeight = div.clientHeight;
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 offsetWidth = div.offsetWidth;
div.innerHTML = 'offsetHeight: ' offsetHeight '
';
div.innerHTML = 'offset Width : ' offsetWidth '
';
var officialtop = div.Offsettop;
Div.Innerhtml = 'OffSetleft' & LT; br/& gt; ' ;
';
var offsetParent = div.offsetParent;
';
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
>
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 IE10With these basic knowledge in hand, we can calculate the position and size of elements.
Coordinates relative to the document and viewportWhen 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.
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;
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
The code is as follows:function getElementPosition(e) {
var x = 0, y = 0;
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.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Linux new version
SublimeText3 Linux latest version

Zend Studio 13.0.1
Powerful PHP integrated development environment