Based on the differences between style. width and offsetWidth in js (detailed description ),

Source: Internet
Author: User

Based on the differences between style. width and offsetWidth in js (detailed description ),

As a beginner, I often wonder whether style. width or offsetWidth is used to obtain the width (height, top value...) of an element.

1. When a style is written in a row, such as <div id = "box" style = "width: 100px">, you can use style. width or offsetWidth to obtain the width of the element.

However, when a style is written in a style sheet, such as # box {width: 100px;}, you can only use offsetWidth to obtain the width of the element, while the value returned by style. width is null.

2. style. widthThe obtained element width is only the div width, excluding the width occupied by border, and padding, and the width value is in px.

The width of the element obtained by offsetWidth is the value of width + border + padding (excluding margin), and the return value is only a value without unit.

The following is an example:

The first result output by the console is 300px.

The second result output by the console is: 308 Note: 300 + 3x2 + 1x2 = 308, with no unit

3. style. widthYou can also set the element width in js, but offsetWidth is not.

The following is an example:

<script>      window.onload = function(){        var box = document.getElementById('box');        box.style.width = '200px';        console.log(box.offsetWidth);        console.log(box.style.width);        box.offsetWidth = '400px';        console.log(box.offsetWidth);        console.log(box.style.width);      }    </script>  

The output result of the console is 208 200px 208 200px, respectively.

That is to say, the width is successfully set through style. width, but the width setting through offsetWidth fails.

The above differences based on style. width and offsetWidth in js (detailed description) are all the content that I have shared with you. I hope to give you a reference and support for the customer's house.

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.