search
HomeWeb Front-endJS TutorialCode to get the position of page elements using Javascript_javascript skills

下面的教程总结了Javascript在网页定位方面的相关知识。

一、网页的绝对大小和相对大小

首先,要明确两个基本概念。

一张网页的全部面积,就是它的绝对大小。通常情况下,网页的绝对大小由内容和CSS样式表决定。

网页的相对大小则是指在浏览器窗口中看到的那部分网页,也就是浏览器窗口的大小,又叫做viewport(视口)。

下图中央的方框就代表浏览器窗口,每次只能显示一部分网页。

(图一 网页的绝对大小和相对大小)

很显然,如果网页的内容能够在浏览器窗口中全部显示(也就是不出现滚动条),那么网页的绝对大小和相对大小是相等的。

二、获取网页的相对大小

网页上的每个元素,都有clientHeight和clientWidth属性,利用它们就可以得到网页的相对大小。这两个属性代表的大小,是指元素的内容部分再加上padding的大小,但是不包括border和滚动条占用的空间。

(图二 clientHeight和clientWidth属性)

因此,document元素的clientHeight和clientWidth属性,就代表了网页的相对大小。

  function getViewport(){
    if (document.compatMode == "BackCompat"){
      return {
        width: document.body.clientWidth,
        height: document.body.clientHeight
      }
    } else {
      return {
        width: document.documentElement.clientWidth,
        height: document.documentElement.clientHeight
      }
    }
  }

上面的getViewport函数就可以返回浏览器窗口的高和宽。使用的时候,有三个地方需要注意:
1)这个函数必须在页面加载完成后才能运行,否则document对象还没生成,浏览器会报错。
2)大多数情况下,都是document.documentElement.clientWidth返回正确值。但是,在IE6的quirks模式中,document.body.clientWidth返回正确的值,因此函数中加入了对文档模式的判断。
3)clientWidth和clientHeight都是只读属性,不能对它们赋值。

三、获取网页的绝对大小

document对象的scrollHeight和scrollWidth属性就是网页的绝对大小,意思就是滚动条滚过的所有长度和宽度。

仿照getViewport()函数,可以写出getPagearea()函数。

  function getPagearea(){
    if (document.compatMode == "BackCompat"){
      return {
        width: document.body.scrollWidth,
        height: document.body.scrollHeight
      }
    } else {
      return {
        width: document.documentElement.scrollWidth,
        height: document.documentElement.scrollHeight
      }
    }
  }

但是,这个函数有一个问题。前面说过,如果网页内容能够在浏览器窗口中全部显示,不出现滚动条,那么网页的绝对大小与相对大小应该相等,即 clientWidth和scrollWidth应该相等。但是实际上,不同浏览器有不同的处理,这两个值未必相等。所以,我们需要取它们之中较大的那个值,因此要对getPagearea()函数进行改写。

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

四、获取网页元素的绝对位置

由于网页大小有绝对和相对之分,所以网页元素的位置也有绝对和相对之分。网页元素的左上角相对于整张网页左上角的坐标,就是绝对位置;相对于浏览器窗口左上角的坐标,就是相对位置。

In Javascript language, the absolute coordinates of web page elements must be calculated. Each element has offsetTop and offsetLeft attributes, which represent the distance between the upper left corner of the element and the upper left corner of the parent container (offsetParent object). Therefore, you only need to accumulate these two values ​​to get the absolute coordinates of the element.

(Figure 3 offsetTop and offsetLeft attributes)

The following two functions can be used to obtain the abscissa and ordinate of the absolute position.

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;
}

Since in tables and iframes, the offsetParent object may not be equal to the parent container, the above function is not applicable to elements in tables and iframes.

5. Obtain the relative position of web elements

After you have the absolute position of an element, it is easy to obtain the relative position. Just subtract the scrolling distance of the scroll bar from the absolute coordinates. The vertical distance of the scroll bar is the scrollTop property of the document object; the horizontal distance of the scroll bar is the scrollLeft property of the document object.

(Figure 4 scrollTop and scrollLeft attributes)

Rewrite the two functions in the previous section accordingly:

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 {
🎜>
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 {
🎜>
return actualTop-elementScrollTop;
}

The scrollTop and scrollLeft attributes can be assigned values, and will automatically scroll the web page to the corresponding position immediately, so they can be used to change the relative position of web page elements. In addition, the element.scrollIntoView() method also has a similar effect, which can make the web page element appear in the upper left corner of the browser window.


6. Quick method to obtain element position

In addition to the above functions, there is also a quick way to get the position of web page elements immediately. That is to use the getBoundingClientRect() method. It returns an object that contains four attributes: left, right, top, and bottom, which respectively correspond to the distance between the upper left corner and lower right corner of the element relative to the upper left corner of the browser window (viewport).

So, the relative position of web page elements is

var

Add the scrolling distance to get the absolute position

var

Currently, IE, Firefox 3.0, and Opera 9.5 all support this method, but Firefox 2.x, Safari, Chrome, and Konqueror do not.

(End)

Statement
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

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.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

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: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

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.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

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

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

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.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

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.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools