我想获取元素的宽度包括元素本身的宽度,边框(如果有),填充和边距(不是JQuery)?
Use Element.getBoundingClientRect() for the width without margins, and Window.getComputedStyle() for the margins:
var d= document.querySelector('div'), cs= getComputedStyle(d); console.log(d.getBoundingClientRect().width + parseFloat(cs.getPropertyValue('margin-left')) + parseFloat(cs.getPropertyValue('margin-right')) );
div { width: 40px; padding: 10px; border: 5px solid green; margin-left: 15px; margin-right: 5px; }
<div> This is a test </div>
Even though the CSS above uses whole numbers only, the result may have decimals. In Chrome, a border style of 5px
results in an actual border of 4.54545450210571px
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.