search
HomeWeb Front-endJS TutorialJavaScript DOM element size and position_Basic knowledge

1 Get the CSS size of the element

1. Get the size of the element through style inline

Copy code The code is as follows:

var box = document.getElementById('box'); // Get element;
box.style.width; box.style.height;

// PS: style can only get the width and height in the CSS style of the inline style attribute. If there is one, get it; if there is none, return empty;

2. Obtain the size of the element through calculation

var style = window.getComputedStyle ? window.getComputedStyle(box,null) : null || box.currentStyle;
      style.width;                                         

// PS: Obtain the size of the element through calculation, regardless of whether it is inline/inline or link, it returns the calculated result;
// If the size is set by itself, it will return the size of the element; if it is not set by itself, non-IE will return the default size, and IE will return auto;


3. Get the size of the element through the cssRules (or rules) attribute in the CSSStyleSheet object;


Copy code The code is as follows: var sheet = document.styleSheets[0]; var sheet var rule = (sheet.cssRules || sheet.rules)[0]; // Get the first rule;
Rule.style.width; Rule.style.width; // 200px;


PS: cssRules can only obtain the width and height of inline and link styles, but cannot obtain inline and calculated styles;

Summary: The above three CSS methods of obtaining element size can only obtain the CSS size of the element, but cannot obtain the actual size of the element itself; such as adding padding/scroll bar/border;

2 Get the actual size of the element

1.clientWidth and clientHeight

This set of attributes can obtain the size of the element's visual area, including the space occupied by the element's content and padding;
box.clientWidth; // 200;
PS: The element size is returned, but there is no unit. The default unit is px;
PS: Regarding the actual size of the element, clientWidth and clientHeight are understood as follows:
​ 1. Add a border to the element, no change, 200;
​ 2. Add outer border to element, no change, 200;
3. Add scroll bar, final value = original size - scroll bar size; 184;
4. Increase padding, final value = original size padding size; 220;
PS: If no CSS width and height are set, then non-IE will include the calculated size of the scroll bar and padding; while IE will return 0;

2.scrollWidth and scrollHeight

This set of attributes can obtain the total height of the element content without scroll bars;
box.scrollWidth;
// PS: Returns the element size, the default unit is px; if no CSS width and height are set, it will get the calculated width and height;

3.offsetWidth and offsetHeight

This set of attributes can return the actual size of the element, including borders/padding and scroll bars;
box.offsetWidth; 200
PS: The element size is returned, and the default unit is px; if no CSS width and height are set, it will get the calculated width and height;
PS: Regarding the actual size of the element, the understanding is as follows:
1. Add border, final value = original size border size; 220;
2. Increase padding, final value = original size padding size; 220;
​ 3. Added external border strongholds, no change;
​ 4. Increase the scroll bar, no change, no decrease;

PS: For obtaining the element size, it is generally more convenient to use block-level elements with CSS sizes set;

3 Get the surrounding size of the element

1.clientLeft and clientTop
// This set of attributes can get the size of the left border and top border set by the element;
box.clientLeft;

2.offsetLeft and offsetTop (offset)

// 这组属性可以获取当前元素边框相对于父元素边框的位置;
  box.offsetLeft;                  // 50;
  // PS:获取元素当前相对于父元素的位置,最好将它设置为定位position:absolute;
  // PS:加上边框和内边距不会影响它的位置,但加上外边据会累加;

  box.offsetParent;                 // 得到父元素;
  // PS:offsetParent中,如果本身父元素是<body>,非IE返回body对象,IE返回html对象;
  // 如果两个元素嵌套,如果上级父元素没有使用定位position:absolute,那么offsetParent将返回body或html对象;

// 如果说在很多层次里,外层已经定位,获取任意一个元素距离页面上的位置,可以不停的向上回溯获取累加来实现;
  box.offsetTop+box.offsetParent.offsetTop;     // 只有两层的情况下;
  // 如果多层的话,就必须使用循环或递归;
  function offsetLeft(element){
    var left = element.offsetLeft;        // 得到第一层距离;
    var parent = element.offsetParent;      // 得到第一个父元素;
    while(parent !== null){            // 判断如果还有上一层父元素;
      left += parent.offsetLeft;        // 将得到的距离累加;
      parent = parent.offsetParent;       // 将父元素也回溯;
    }                       // 然后循环;
    return left;                 // 得到最终距离;
  }

3.scrollTop and scrollLeft

// 这组属性可以获取被滚动条隐藏的区域大小,也可设置定位到该区域;
  box.scrollTop;                  // 获取滚动内容上方的位置;

// 设置滚动条滚动到最初始的位置;
  function scrollStart(element){
    if(element.scrollTop != 0){
      element.scrollTop = 0;
    }
  }

Four getBoundingClientRect() method

// 这个方法返回一个矩形对象,包含四个属性:left/top/right和bottom;
// 分别表示元素各边与页面上边和左边的距离;
  var box = document.getElementById('box');
  alert(box.getBoundingClientRect().top);    // 元素上边距离页面上边的距离;
  alert(box.getBoundingClientRect().right);   // 元素右边距离页面左边的距离;
  alert(box.getBoundingClientRect().bottom);   // 元素下边距离页面上边的距离;
  alert(box.getBoundingClientRect().left);    // 元素左边距离页面左边的距离;
  // PS:IE/Firefox/Opera/Chrome/Safari都支持;
  // 但在IE中,默认坐标从(2,2)开始计算,导致最终距离比其他浏览器多出两个像素;
  document.documentElement.clientTop;      // 非IE为0,IE为2;
  document.documentElement.clientLeft;      // 非IE为0,IE为2;
// 兼容getBoundingClientRect()
  function getRect(element){
    var rect = element.getBoundingClientRect();
    var top = document.documentElement.clientTop;
    var left = document.documentElement.clientLeft;
    return {
      top:rect.top-top,           // 元素上边距-页面的上边距(0-0或2-2);
      bottom:rect.bottom-top,
      left:rect.left-left,         // 元素左边距-页面的左边距(0-0或2-2);
      right:rect.right-left
    }
  };

Five Summary

1. Offset dimension: includes all visible space occupied by the element on the screen;

The visible size of an element is determined by its height and width, including padding/scrollbars and borders;
2. Client dimension: refers to the space occupied by the element content and its padding;
3.Scroll size (scroll dimension): The size of the element containing the scrolling content;

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development 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.