offsetWidth、clientWidth、scrollWidth如何计算
先贴一下测试用html,很简单
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> div{ height: 100px; width: 300px; padding: 10px; border: 5px solid black; outline: yellow solid 5px; /* overflow-y: scroll; */ } span{ /*display:block; width: 100px;*/ padding: 10px; border: 1px solid black; } </style> </head> <body> <div> This is a div.<br/> hahahhahahahahahahahahahahahahahahahahahahahahahahahahahahah<br/> Test Content.<br/> Test Content.<br/> Test Content.<br/> Test Content.<br/> </div> <span> This is a span. </span> <script> let div = document.getElementsByTagName("div")[0]; let span = document.getElementsByTagName("span")[0]; console.log(`div的offsetWidth${div.offsetWidth}`); console.log(`span的offsetWidth${span.offsetWidth}`); console.log(`div的clientWidth${div.clientWidth}`); console.log(`span的clientWidth${span.clientWidth}`); console.log(`div的scrollWidth${div.scrollWidth}`); console.log(`span的scrollWidth${span.scrollWidth}`); </script> </body> </html>
- offsetWidth

MDN的解释:The HTMLElement.offsetWidth read-only property returns the layout width of an element. Typically, an element’s offsetWidth is a measurement which includes the element borders, the element horizontal padding, the element vertical scrollbar (if present, if rendered) and the element CSS width. If the element is hidden (for example, by style.display on the element or one of its ancestors to “none”), then 0 is returned.
- clientWidth

MDN的解释:The Element.clientWidth property is zero for elements with no CSS or inline layout boxes, otherwise it’s the inner width of an element in pixels. It includes padding but not the vertical scrollbar (if present, if rendered), border or margin.
- scrollWidth
这三个属性的都会对值进行四舍五入
This property will round the value to an integer. If you need a fractional value, use element.getBoundingClientRect().
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/231532.html原文链接:https://javaforall.net
