確定元素的尺寸

有幾種屬性可以用來確定元素的寬度和高度,而選擇哪種屬性適合您的需求可能很棘手。本文旨在幫助您做出決定。請注意,所有這些屬性都是隻讀的。如果您想設定元素的寬度和高度,請使用 widthheight 或覆蓋屬性 min-widthmax-width,以及 min-heightmax-height 屬性。

它佔用了多少空間?

如果您需要知道元素佔用的總空間,包括可見內容的寬度、捲軸(如果有)、內邊距和邊框,您應該使用 HTMLElement.offsetWidthHTMLElement.offsetHeight 屬性。大多數情況下,當元素沒有應用任何變換時,它們與 Element.getBoundingClientRect() 的寬度和高度相同。在應用了變換的情況下,offsetWidthoffsetHeight 返回的是元素的佈局寬度和高度,而 getBoundingClientRect() 返回的是渲染寬度和高度。例如,如果元素具有 width: 100px;transform: scale(0.5);getBoundingClientRect() 將返回 50 作為寬度,而 offsetWidth 將返回 100。另一個區別是 offsetWidthoffsetHeight 會將值四捨五入到整數,而 getBoundingClientRect() 提供更精確的小數值。

How the offsetWidth and offsetHeight properties are determined, considering padding, borders, and margin sizes

顯示內容的尺寸是多少?

如果您需要知道實際顯示內容佔用的空間,包括內邊距,但不包括邊框、外邊距或捲軸,您應該使用 Element.clientWidthElement.clientHeight 屬性。

How the clientWidth and clientHeight properties are determined, considering padding, borders, and margin sizes

內容有多大?

如果您需要知道內容的實際尺寸,而不考慮當前可見的部分,您需要使用 Element.scrollWidthElement.scrollHeight 屬性。這些屬性返回元素全部內容的寬度和高度,即使由於使用了捲軸,目前只有一部分內容可見。

例如,如果一個 600x400 畫素的元素顯示在一個 300x300 畫素的滾動容器中,scrollWidth 將返回 600,而 scrollHeight 將返回 400。

另見