JavaScript gets element size and size operations Summary _javascript Tips

Source: Internet
Author: User

First, get the inline style of the element

Copy Code code 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 Code code 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, return the default width and height in non-ie browsers. Return the auto string below IE

Get <link> and <style> tag write style

Copy Code code 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 the inline and calculated styles.

Summary: The above three kinds of CSS to get the size of the element method, can only get the CSS size of elements, but can not get the actual size of the element itself. such as the addition of the inner margin, scroll bar, border and so on.

Get the actual size of the element

1. ClientWidth and ClientHeight
This set of properties gets the size of the element's viewable area, and the amount of space that the element's content and the inner margin occupy. Return the element size, but no units, the default unit is PX, if you force set units, such as 100em, it will return the size of PX. (CSS is acquired by the style you set.) For the actual size of the element, ClientWidth and ClientHeight understand the following:
A. Add borders, no changes;
B. Increase the outer margin without change;
C. Increase the scroll bar, the final value is equal to the original size minus the size of the scroll bar;
D. Increase the inner margin, the final value is equal to the original size plus the size of the inner margin;

Copy Code code as follows:

<div id= "Test" ></div>
#test {
Background-color:green;
width:200px;
height:200px;
Border:solid 5px Red; /* Corresponds to a understanding, results: 200,200 */
margin:10px; /* Corresponds to B understanding, Result: 200,200*/
padding:20px; /* corresponding to C understanding, results: 240,240*/
Overflow:scroll; /* Corresponds to D understanding, Result: 223,223,223=200 (CSS size) +40 (both sides of the margin)-17 (scroll bar 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, then not IE browser will calculate the scroll bar and the size of the interior margin, and IE browser returned 0 (IE8 has been repaired).

2. ScrollWidth and ScrollHeight
    This set of properties can get the element size of the scrolling 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 computed widths and heights. For the actual size of the element, ScrollWidth and ScrollHeight understand the following:
    1. Add a border, different browsers have different interpretations (the following in the IE8 normal operation, IE6 operation is not normal):
Firefox and Opera browsers will increase the size of the border, 220x220
B) ie, chrome and safari browsers will ignore the border size, 200x200
C, ie browser only displays the height of its original content, 200X18 (IE8 has modified the problem)
    2. Increase the inner margin, the final value is equal to the original size plus the size of the inner margin, 220x220,ie is 220x38
    3. Increase the scroll bar, the final value is equal to the original size minus the scroll bar size, 184x184,ie 184x18
    4. Increase the outside, no change.
    5. Increase content overflow, Firefox, chrome and IE get the actual content height, opera is smaller than the top three browsers, and Safari is larger than the top three browsers.

3. Offsetwidth and Offsetheight
This set of properties returns the actual size of the element, including borders, margins, and scroll bars. The element size is returned, and the default unit is PX. If no CSS is set and height, he will get the width and height of the calculation. 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 size of the inner margin, 220;
3. Increase outside, no change;
4. Increase the scroll bar, no change, will not reduce;
For the acquisition of element size, it is generally a block-level element and is convenient for elements with CSS size. If it's an inline element (inline) or an element that doesn't have a size set, it's especially troublesome, so be advised to pay attention when used.

Copy Code code as follows:

<div id= "test" >test div element</div>
#test {
Background-color:green;
width:200px;
height:200px;
Border:solid 10px Red; /* Results: 220,220*/
margin:10px; /* Results: 220,220 (no change) * *
padding:10px; /* Results: 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 surrounding size of elements
1. ClientLeft and ClientTop get border size
This set of properties can get the size of the left and top borders of the element set. Only the left and top groups are currently available, and no right and bottom are available. If the width of the four edges is different, it can be obtained directly by the calculated style, or by subtracting the element size by 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 Code code 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 currently relative to the parent element, preferably setting it to position position:absolute; otherwise, different browsers have different interpretations.
A, the position is set to absolute, all browsers return the same value. Such as:

Copy Code code 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 the inner margin will not affect its position, but plus the outside will accumulate.

3, Box.offsetparent get the parent element
In Offsetparent, if the parent element is <BODY>, not IE returns the Body object, IE (IE6) returns the HTML object. If two elements are nested, offsetparent will return the body object or HTML object if the parent element is not using the Position:absolute. So, when getting offsetleft and offsettop, CSS positioning is important.
If, at many levels, the outer layer is positioned, how do we get the distance between the elements within the body or the HTML element? That is, to get any element from the position on the page. So we can write a function to get the sum up by constantly backtracking up.

Copy Code code as follows:

Box.offsettop + Box.offsetParent.offsetTop; Only a two-storey 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 an upper 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 the loop
return to left;
}

4.scrollTop and ScrollLeft
This set of properties gets the area size of the scroll bar that is hidden (the area above the scroll bar), and can also be set to navigate to the area. If you want the scroll bar to scroll to the initial position, you can write a function:

Copy Code code as follows:

function Scrollstart (Element) {
if (element.scrolltop!= 0) {
element.scrolltop = 0;
}
}

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

Copy Code code as follows:

var Box=document.getelementbyid (' box '); Get element
Alert (Box.getboundingclientrect (). top); The distance above the top of the page from the top of the element
Alert (Box.getboundingclientrect (). right); The distance from the right of the element to the left of the page
Alert (Box.getboundingclientrect (). bottom); The distance between the bottom of the element and the top of the page
Alert (Box.getboundingclientrect (). left); The distance from the left of the page to the left of the element

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

Copy Code code as follows:

Document.documentElement.clientTop; Non ie for 0,ie is 2
Document.documentElement.clientLeft; Non ie for 0,ie is 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 outside, inner margins, borders, and scrollbars to test all browsers for consistency.

The above is the entire content described in this article, I hope that the small partners can enjoy.

Related Article

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.