


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)을 포함하는 객체를 반환합니다. 이 속성은 각각 브라우저 창(뷰포트)의 왼쪽 상단 모서리를 기준으로 요소의 왼쪽 상단 모서리와 오른쪽 하단 모서리 사이의 거리에 해당합니다. .
그래서 웹페이지 요소의 상대적인 위치는

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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.

Zend Studio 13.0.1
Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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),
