As a beginner, I often encounter the confusion of whether to use style.width or offsetWidth when getting the width (height, top value...) of a certain element. This article. I will bring you an article based on the difference between style.width and offsetWidth in js (detailed explanation). The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. I hope everyone can better understand the difference between style.width and offsetWidth in js.
1. When the style is written inline, such as
, you can use style.width or offsetWidth to get the width of the element.
However, when the style is written in the style sheet, such as #box{ width: 100px; }, offsetWidth can only be used to obtain the width of the element, and the value returned by style.width is empty.
2. style.width The width of the element obtained is only the width of p, excluding the width occupied by border, and padding, and the width value is in px of.
offsetWidth The width of the element obtained is the value of width+border+padding (excluding margin), and the return value is only a numerical value without a unit.
As shown in the following example:
<head> <script> window.onload = function(){ var box = document.getElementById('box'); console.log(box.style.width); console.log(box.offsetWidth); } </script> </head> <body> <p id="box" style="width:300px; height: 300px; padding:3px; margin: 1px; border: 1px solid red;"></p> </body>
The first result output by the console is : 300px
The second result output by the console is: 308 Note: 300+ 3x2 +1x2 = 308, without unit
##3. style.width can also be used to set the width of elements in js, but offsetWidth cannot.
As shown in the following 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> </head> <body> <p id="box" style="width:300px; height: 300px; padding:3px; margin: 2px; border: 1px solid red;"></p> </body>
Summary of some compatibility and error-prone issues in js
Discussion on components and templates in Vue.js
Detailed explanation of functions apply and call in Js
The above is the detailed content of Detailed explanation of the difference between style.width and offsetWidth in js. For more information, please follow other related articles on the PHP Chinese website!