JavaScript obtains the actual width and height of html elements.

Source: Internet
Author: User

JavaScript obtains the actual width and height of html elements.

1. JavaScript to obtain the width and height of html elements

1. The width and height are written in the style table, for example, # div1 {width: 120px ;}. In this case, the width cannot be obtained through # div1.style. width, but the width can be obtained through # div1.offsetWidth.
2. width and height are written in the row, such as style = "width: 120px;". In this case, the width can be obtained through the above two methods.

Summary,ClientWidthAndOffsetWidthThe style is written in the style sheet or in the row, so we 'd better use these two attributes when getting the element width and height. Note that attributes not written in the row style cannot be obtained through I **. style. atrr.
Currently, the front-end style is rarely written directly into the style, and they are all written in the style sheet. If the style you want to obtain does not correspond to (like # div1.style. width # div1.offsetWidth), you can only retrieve the attributes of the style sheet without using a browser, you can try to search for "JS get style attributes" and so on.

Code:
Var o = document. getElementById ("view ");
Var h = o. offsetHeight; // height
Var w = o. offsetWidth; // width

 

 

2. Relationship between width, clientWidth, and offsetWidth

Width is the content width of an html element.

ClientWidth = width + padding
OffsetWidth = width + padding + border

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.