offsetWidth 属性
offsetWidth 属性是 HTML DOM 中的一个属性,它可以用来获取元素的宽度值(以像素为单位),包括元素边框、填充和滚动条,但不包括外边距。
使用方法
offsetWidth 属性可以通过元素的 style 属性访问,例如:
var myElement = document.getElementById("myDiv"); var myDivWidth = myElement.offsetWidth;
也可以通过访问元素的 clientWidth 属性来获取宽度,但是 clientWidth 属性不包括元素的边框,所以得到的宽度会比 offsetWidth 属性小:
var myElement = document.getElementById("myDiv"); var myDivWidth = myElement.clientWidth;
示例
下面的例子展示了 offsetWidth 属性的用法:
This is a div element.
Click the button to get the width of the div element.
上面的例子使用了 offsetWidth 属性,当点击按钮时,会在页面上显示 div 元素的宽度(以像素为单位)。