HTML DOM Element offsetWidth 屬性

定義和用法

offsetWidth 屬性返回元素的可視寬度(以像素為單位),包括內邊距、邊框和滾動條,但不包括外邊距。

offsetWidth 屬性是只讀的。

請參閱:CSS 框模型教程

offsetParent

所有塊級元素都報告相對于偏移父級的偏移量:

  • offsetTop
  • offsetLeft
  • offsetWidth
  • offsetHeight

偏移父級指的是最近的具有非靜態位置的祖先。

如果不存在偏移父級,則偏移量是相對于文檔正文的。

另請參閱:

offsetHeight 屬性

offsetParent 屬性

offsetTop 屬性

offsetLeft 屬性

clientTop 屬性

clientLeft 屬性

clientWidth 屬性

clientHeight 屬性

實例

例子 1

獲取 "myDIV" 的高度和寬度,包括內邊距和邊框:

const elmnt = document.getElementById("myDIV");
let text = "Height with padding and border: " + elmnt.offsetHeight + "px<br>";
text += "Width with padding and border: " + elmnt.offsetWidth + "px";

親自試一試

例子 2

clientHeight/clientWidth 與 offsetHeight/offsetWidth 的區別

不帶滾動條:

const elmnt = document.getElementById("myDIV");
let text = "";
text += "Height with padding: " + elmnt.clientHeight + "px<br>";
text += "Height with padding and border: " + elmnt.offsetHeight + "px<br>";
text += "Width with padding: " + elmnt.clientWidth + "px<br>";
text += "Width with padding and border: " + elmnt.offsetWidth + "px";

親自試一試

帶滾動條:

const elmnt = document.getElementById("myDIV");
let text = "";
text += "Height with padding: " + elmnt.clientHeight + "px<br>";
text += "Height with padding, border and scrollbar: " + elmnt.offsetHeight + "px<br>";
text += "Width with padding: " + elmnt.clientWidth + "px<br>";
text += "Width with padding, border and scrollbar: " + elmnt.offsetWidth + "px";

親自試一試

語法

element.offsetWidth

返回值

類型 描述
數字 元素的可視寬度(以像素計),包括內邊距、邊框和滾動條。

瀏覽器支持

所有瀏覽器都支持 element.offsetWidth

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
支持 支持 支持 支持 支持 支持