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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

See all articles