


Use Javascript to get the specific location of page elements_javascript skills
In the process of making a web page, you sometimes need to know the exact location of an element on the web page.
The following tutorial summarizes the relevant knowledge of Javascript in web page positioning.
1. The size of the web page and the size of the browser window
First of all, two basic concepts must be clarified.
The entire area of a web page is its size. Typically, the size of a web page is determined by content and CSS style sheets.
The size of the browser window refers to the area of the web page seen in the browser window, also called the viewport.
Obviously, if the content of the web page can be fully displayed in the browser window (that is, no scroll bars appear), then the size of the web page and the size of the browser window are equal. If the entire page cannot be displayed, scroll the browser window to display portions of the web page.
2. Get the size of the web page
Every element on the web page has clientHeight and clientWidth attributes. These two attributes refer to the visual area occupied by the content part of the element plus padding, excluding the space occupied by the border and scroll bar.
(Figure 1 clientHeight and clientWidth attributes)
Therefore, the clientHeight and clientWidth attributes of the document element represent the size of the web page.
function getViewport(){
if (document. compatmode == "backcompat") {
Return {
Width: Document.body.clientWidth,
Height: Document.Clientheigh
} Else { N> Return { Width: document.documentedLement.clientWidth,
Height: Document.documentedlement.clientheight
}
}
GetView above. The port function can return the browser The height and width of the window. There are three things you need to pay attention to when using it:
1) This function must be run after the page is loaded, otherwise the document object has not been generated and the browser will report an error.
2) In most cases, document.documentElement.clientWidth returns the correct value. However, in the quirks mode of IE6, document.body.clientWidth returns the correct value, so the judgment of the document mode is added to the function.
3) clientWidth and clientHeight are both read-only properties and cannot be assigned a value.
3. Another way to get the size of the web page
Each element on the web page also has scrollHeight and scrollWidth attributes, which refer to the visual area of the element including the scroll bar. . Then, the scrollHeight and scrollWidth properties of the document object are the size of the web page, which means the entire length and width of the scroll bar.
Imitating the getViewport() function, you can write the getPagearea() function.
Copy code
Height: Document.body.ighheighheighry { Return {
width: document.documentElement.scrollWidth,
Height: document.documentElement.scrollHeight
}
}
}
However, there is a problem with this function. If the content of the web page can be fully displayed in the browser window without scroll bars, then the clientWidth and scrollWidth of the web page should be equal. But in fact, different browsers have different processing methods, and these two values are not necessarily equal. Therefore, we need to take the larger value among them, so we need to rewrite the getPagearea() function.
Copy code
The code is as follows:
function getPagearea(){
if (document.compatMode == "BackCompat"){
return {
width: Math.max(document.body.scrollWidth,
document.body.clientWidth),
height: Math.max(document.body.scrollHeight,
document.body.clientHeight)
}
} else {
return {
width: Math.max(document.documentElement.scrollWidth,
document.documentElement.clientWidth),
height: Math.max(document.documentElement.scrollHeight,
document.documentElement.clientHeight)
}
}
}
四、获取网页元素的绝对位置
网页元素的绝对位置,指该元素的左上角相对于整张网页左上角的坐标。这个绝对位置要通过计算才能得到。
首先,每个元素都有offsetTop和offsetLeft属性,表示该元素的左上角与父容器(offsetParent对象)左上角的距离。所以,只需要将这两个值进行累加,就可以得到该元素的绝对坐标。

(图二 offsetTop和offsetLeft属性)
下面两个函数可以用来获取绝对位置的横坐标和纵坐标。
function getElementLeft(element){
var actualLeft = element.offsetLeft;
var current = element.offsetParent;
while (current !== null){
actualLeft = current.offsetLeft;
current = current.offsetParent;
}
return actualLeft;
}
function getElementTop(element){
var actualTop = element.offsetTop;
var current = element.offsetParent;
while (current !== null){
actualTop = current.offsetTop;
current = current.offsetParent;
}
return actualTop;
}
由于在表格和iframe中,offsetParent对象未必等于父容器,所以上面的函数对于表格和iframe中的元素不适用。
五、获取网页元素的相对位置
网页元素的相对位置,指该元素左上角相对于浏览器窗口左上角的坐标。
有了绝对位置以后,获得相对位置就很容易了,只要将绝对坐标减去页面的滚动条滚动的距离就可以了。滚动条滚动的垂直距离,是document对象的scrollTop属性;滚动条滚动的水平距离是document对象的scrollLeft属性。

(图三 scrollTop和scrollLeft属性)
对上一节中的两个函数进行相应的改写:
function getElementViewLeft(element){
var actualLeft = element.offsetLeft;
var current = element.offsetParent;
while (current !== null){
actualLeft = current.offsetLeft;
current = current.offsetParent;
}
if (document.compatMode == "BackCompat"){
var elementScrollLeft=document.body.scrollLeft;
} else {
var elementScrollLeft=document.documentElement.scrollLeft;
}
return actualLeft-elementScrollLeft;
}
function getElementViewTop(element){
var actualTop = element.offsetTop;
var current = element.offsetParent;
while (current !== null){
actualTop = current. offsetTop;
current = current.offsetParent;
}
if (document.compatMode == "BackCompat"){
var elementScrollTop=document.body.scrollTop;
} else {
var elementScrollTop=document.documentElement.scrollTop;
}
return actualTop-elementScrollTop;
}
scrollTop 및 scrollLeft 속성에 값을 할당할 수 있으며 웹페이지를 해당 위치로 즉시 자동 스크롤하므로 웹페이지 요소의 상대적 위치를 변경하는 데 사용할 수 있습니다. 또한 element.scrollIntoView() 메서드도 유사한 효과를 가지며, 이를 통해 웹 페이지 요소가 브라우저 창의 왼쪽 상단에 표시되도록 할 수 있습니다.
6. 요소의 위치를 빠르게 가져오는 방법
위의 기능 외에도 웹페이지의 위치를 빠르게 가져오는 방법이 있습니다. 즉시 요소.
getBoundingClientRect() 메소드를 사용하는 것입니다. 이는 네 가지 속성(left, right, top, Bottom)을 포함하는 객체를 반환합니다. 이 속성은 각각 브라우저 창(뷰포트)의 왼쪽 상단 모서리를 기준으로 요소의 왼쪽 상단 모서리와 오른쪽 하단 모서리 사이의 거리에 해당합니다. .
그래서 웹페이지 요소의 상대적인 위치는

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

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver CS6
Visual web development tools

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.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft