JavaScript get element size and size operations summary

Source: Internet
Author: User

First, get the inline style of the element

Copy CodeThe code is as follows:
var obj = document.getElementById ("test");
Alert (obj.height + "\ n" + obj.width);
200px 200px typeof=string just show the values in the Style property

Second, get the calculated style

Copy CodeThe code is as follows:
var obj = document.getElementById ("test");
var style = null;
if (window.getComputedStyle) {
style = window.getComputedStyle (obj, null); Non-IE
} else {
style = Obj.currentstyle; Ie
}
Alert ("width=" + style.width + "\nheight=" + style.height);

Note: If you do not set the width and height of the element, the default width and height are returned in non-IE browsers. Returns the auto string under IE

Third, get <link> and <style> label write style

Copy CodeThe code is as follows:
var obj = document.stylesheets[0]; Number of [object Stylesheetlist] style sheets <link>var rule = null;//[Object Cssrule]
if (obj.cssrules) {
Rule = obj.cssrules[0]; Non IE [object cssrulelist]
} else {
Rule = obj.rules[0]; IE [Object Cssrulelist]
}
alert (rule.style.width);

Cssrules (or rules) can only get the width and height of inline and link styles, and cannot get into inline and computed styles.

Summary: The above three kinds of CSS get the element size method, can only get the element's CSS size, but cannot get the actual size of the element itself. For example, with padding, scroll bars, borders and so on.

Iv. getting the actual size of the element

1. ClientWidth and ClientHeight
This set of properties can get the size of the visual area of an element, and the amount of space occupied by the element's content and padding. Returns the element size, but no unit, the default unit is PX, if you forcibly set the unit, such as 100EM, it will return the size of PX. (CSS gets it, you get it according to the style you set). For the actual size of the element, clientwidth and ClientHeight are understood as follows:
A. Increase the border, no change;
B. Increase margin, no change;
C. Increase the scroll bar, the final value is equal to the original size minus the scroll bar size;
D. Increase the inner margin, the final value is equal to the original size plus the size of the inner margin;

Copy CodeThe code is as follows:
<div id= "Test" ></div>
#test {
Background-color:green;
width:200px;
height:200px;
Border:solid 5px Red; /* Corresponds to a understanding, Result: 200,200 */
margin:10px; /* Corresponds to B understanding, Result: 200,200*/
padding:20px; /* corresponds to C comprehension, result: 240,240*/
Overflow:scroll; /* Corresponds to D understanding, Result: 223,223,223=200 (CSS size) +40 (padding on both sides)-17 (ScrollBar width) */
}
Window.onload = function () {
var obj = document.getElementById ("test");
Alert (Obj.clientwidth + "," + obj.clientheight);
};

Note: If you do not set any CSS width and height, the non-IE browser calculates the size of the scroll bar and padding, and IE returns 0 (IE8 has been repaired).

2. ScrollWidth and ScrollHeight
    This set of properties can get the element size of the scrolled content (visible content). The element size is returned, and the default unit is PX. If you do not set the width and height of any CSS, it will get the calculated widths and heights. For the actual size of the element, ScrollWidth and ScrollHeight are understood as follows:
    1. Add a border, different browsers have different interpretations (the following in the IE8 run normally, IE6 not working properly):
a) Firefox and Opera browser will increase the size of the border, 220x220
B) ie, chrome and Safari browser will ignore the border size, 200x200
C) IE browser only shows the height of its original content, 200X18 (IE8 has modified the issue)
    2. Increase the padding, and the final value will be equal to the original size plus the padding size, 220x220,ie to 220x38
    3. Increase the scrollbar, the final value will be equal to the original size minus the scrollbar size, 184x184,ie to 184x18
    4. Increase the margin, no change.
    5. Add content overflow, Firefox, chrome and IE get the actual content height, opera compared to the top three browser to get a small height, safari than the top three browsers get high.

3. Offsetwidth and Offsetheight
This set of properties returns the actual size of the element, including the bounding rectangle, padding, and scroll bars. The element size is returned, and the default unit is PX. If you do not set any CSS width and height, he will get the calculated widths and heights. For the actual size of the element, Offsetwidth and offsetheight understand the following:
1. Increase the border, the final value will be equal to the original size plus the border size, 220;
2. Increase the inner margin, the final value will be equal to the original size plus the inner margin size, 220;
3. Increase the margin, without change;
4. Add scroll bar, no change, no decrease;
For the acquisition of the element size, it is generally a block-level element and is more convenient to set the element of the CSS size. It is especially troublesome to have inline elements (inline) or elements that are not set in size, so it is recommended to use them.

Copy CodeThe code is as follows:
<div id= "test" >test div element</div>
#test {
Background-color:green;
width:200px;
height:200px;
Border:solid 10px Red; /* Result: 220,220*/
margin:10px; /* Results: 220,220 (no change) */
padding:10px; /* Result: 240,240*/
Overflow:scroll; /* Results: 240,240 (no change) */
}
Window.onload = function () {
var obj = document.getElementById ("test");
Alert (Obj.offsetwidth + "," + obj.offsetheight);
};

V. Get the size of the element perimeter
1. ClientLeft and ClientTop get border size
This set of properties lets you get the size of the left and top borders of the element. Currently only provides left and top this group, and does not provide right and bottom. If the width of the four edges is different, it can be obtained directly from the calculated style, or by subtracting the element size from the above three groups.
Width of right border: Obj.offsetwidth-obj.clientwidth-obj.clientleft
Width of bottom border: obj.offsetheight-obj.clientheight-obj.clienttop

Copy CodeThe code is as follows:
<div id= "test" >test div element</div>
#test {
Background-color:green;
width:200px;
height:200px;
Border-top:solid 10px Red;s
Border-right:solid 20px #00ff00;
Border-bottom:solid 30px Blue;
Border-left:solid 40px #808080;
}
Window.onload = function () {
var obj = document.getElementById ("test");
Alert (Obj.clientleft + "," + obj.clienttop); 40,10
};

2. Offsetleft and offsettop
This set of properties can get the position of the current element relative to the parent element. Gets the position of the element that is currently relative to the parent element, preferably set to locate Position:absolute, otherwise different browsers will have different interpretations.
A, set position to absolute, then all browsers return the same value. Such as:

Copy CodeThe code is as follows:
<div id= "test" >test div element</div>
#test {
Background-color:green;
width:200px;
height:200px;
Position:absolute;
left:30px;
top:20px;
}
Window.onload = function () {
var obj = document.getElementById ("test");
Alert (Obj.offsetleft + "," + obj.offsettop); 30, 20
};

b, plus the border and padding will not affect its position, but the addition of the outside will accumulate.

3. Box.offsetparent Get Parent Element
In Offsetparent, if the parent element itself is <body>, non IE returns the Body object, IE (IE6) returns the HTML object. If two elements are nested, offsetparent returns a Body object or an HTML object if the parent element is not using the anchor position:absolute. So, when it comes to getting offsetleft and offsettop, CSS positioning is important.
If, in many layers, the outer layer has been positioned, how can we get the distance between the inner element and the body or HTML element? That is, to get any element on the page from the position. Then we can write the function, which is realized by continuous upward backtracking to get the summation.

Copy CodeThe code is as follows:
Box.offsettop + Box.offsetParent.offsetTop; Only two stories in the case

function Offsetleft (Element) {
var left = Element.offsetleft; Get the first layer of distance
var parent = element.offsetparent; Get the first parent element
while (parent!== null) {//If there is a previous layer of parent element
Left + = Parent.offsetleft; Add up the distance of this layer
parent = parent.offsetparent; Get the parent element of this layer
}//Then continue looping
return left;
}

4.scrollTop and ScrollLeft
This set of properties can get the area size of the scroll bar being hidden (the area above the scrollbar), or it can be set to the area. If you want the scroll bar to scroll to the initial position, you can write a function:

Copy CodeThe code is as follows:
function Scrollstart (Element) {
if (element.scrolltop! = 0) {
element.scrolltop = 0;
}
}

5, Getboundingclientrect ()
This method returns a rectangle object that contains four properties: Left, top, right, and bottom. Represents the distance between the edges of the element and the top and left sides of the page, respectively.

Copy CodeThe code is as follows:
var Box=document.getelementbyid (' box '); Get element
Alert (Box.getboundingclientrect (). top); The distance from the top of the page to the top of the element
Alert (Box.getboundingclientrect (). right); Distance to the right of the element from the left side of the page
Alert (Box.getboundingclientrect (). bottom); The distance from the top of the page below the element
Alert (Box.getboundingclientrect (). left); Distance from left side of element to the left of the page

Note: IE, firefox3+, Opera9.5, Chrome, Safari support, in IE, the default coordinates are calculated from (2,2), resulting in a final distance of two pixels more than other browsers, we need to do a compatibility.

Copy CodeThe code is as follows:
Document.documentElement.clientTop; Non-IE is 0,ie for 2
Document.documentElement.clientLeft; Non-IE is 0,ie for 2
Functionggetrect (Element) {
var rect = Element.getboundingclientrect ();
var top = Document.documentElement.clientTop;
var left= document.documentElement.clientLeft;
return{
Top:rect.top-top,
Bottom:rect.bottom-top,
Left:rect.left-left,
Right:rect.right-left
}
}

Add the margin, padding, borders, and scrollbars, respectively, to test whether all browsers are consistent.

JavaScript get element size and size operations summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.