Home Web Front-end JS Tutorial Use Javascript to get the specific location of page elements_javascript skills

Use Javascript to get the specific location of page elements_javascript skills

May 16, 2016 pm 05:10 PM
element position

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.
Use Javascript to get the specific location of page elements_javascript skills
(Figure 1 clientHeight and clientWidth attributes)

Therefore, the clientHeight and clientWidth attributes of the document element represent the size of the web page.

Copy code The code is as follows:

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
The code is as follows: Function getPagearea(){ if (document. compatmode == "backcompat") {
Return {
Width: Document.body.scrollwidth,
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对象)左上角的距离。所以,只需要将这两个值进行累加,就可以得到该元素的绝对坐标。
Use Javascript to get the specific location of page elements_javascript skills 
(图二 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属性。
Use Javascript to get the specific location of page elements_javascript skills 
(图三 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)을 포함하는 객체를 반환합니다. 이 속성은 각각 브라우저 창(뷰포트)의 왼쪽 상단 모서리를 기준으로 요소의 왼쪽 상단 모서리와 오른쪽 하단 모서리 사이의 거리에 해당합니다. .

그래서 웹페이지 요소의 상대적인 위치는
코드를 복사하세요 코드는 다음과 같습니다. 🎜>
var



코드 복사

코드는 다음과 같습니다. var X= this.getBoundingClientRect().left document.documentElement.scrollLeft; var Y =this.getBoundingClientRect().top document.documentElement.scrollTop;
현재 IE , Firefox 3.0 및 Opera 9.5는 모두 이 방법을 지원하며 Firefox 2.x, Safari, Chrome 및 Konqueror는 지원하지 않습니다.
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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

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.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

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.

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

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.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

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 vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

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.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 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.

See all articles