简体   繁体   English

HTML中style.width和offsetwidth的区别?

[英]Difference between style.width and offsetwidth in HTML?

I notice that offsetwidth is a slightly bigger number. 我注意到offsetwidth是一个略大的数字。 Similarly for style.height and offsetheight . 同样适用于style.heightoffsetheight

offsetWidth returns computed element's width, while el.style.width just returns width property defined in element.style by javascript and does not reflect real element's dimensions. offsetWidth计算元素的宽度,而返回el.style.width只是通过返回element.style定义width属性javascript ,并不能反映真实的元件的尺寸。

This means that if you will try to get a width of the element by accessing el.style , you will probably get nothing ( sample ), even if the width was defined in your CSS. 这意味着如果您尝试通过访问el.style来获取元素的宽度,即使在CSS中定义了宽度,您也可能得不到任何内容( sample )。 You will get the number only if it was defined in el.style by javascript . 只有通过javascriptel.style中定义时,才能获得该数字。

Furthermore, offsetWidth gives you real width of your element, including padding and border if you use content-box css box model which is default value for box-sizing . 此外, offsetWidth为您提供元素的实际宽度,包括paddingborder如果您使用content-box css box model ,它是box-sizing默认值。 So you can think about that like you set width of the contents of the element and padding/border go on top of that ( sample ). 所以你可以考虑一下,就像设置元素内容的widthpadding/bordersample )。

If you are using border-box css box model , you set the total width of the element, including padding and border make the content area smaller ( sample ). 如果使用border-box css box model ,则设置元素的总宽度,包括paddingborder使内容区域变小( sample )。 So, in this case, offsetWidth and el.style.width would return exactly the same numbers (if el.style.width was previously set by javascript ). 因此,在这种情况下, offsetWidthel.style.width将返回完全相同的数字(如果el.style.width之前由javascript设置)。

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. 通常,元素的offsetWidth是一个度量,它包括元素边框,元素水平填充,元素垂直滚动条(如果存在,如果呈现)和元素CSS宽度。

Source: https://developer.mozilla.org/en/DOM/element.offsetWidth 资料来源: https//developer.mozilla.org/en/DOM/element.offsetWidth


So, it's the width of your element with border and padding included. 所以,它是包含边框和填充的元素的宽度。 Same thing for height. 身高也一样。

offsetWidth is a measurement in pixels of the element's CSS width, including any borders, padding, and vertical scrollbars. offsetWidth是元素CSS宽度的度量单位,包括任何边框,填充和垂直滚动条。

clientWidth is the inner width (ie. the space inside an element including padding but excluding borders and scrollbars) clientWidth是内部宽度(即元素内部的空间,包括填充但不包括边框和滚动条)

with only return the css with defined 只返回定义的css

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM