JavaScriptのclientWidthとclientHeight
提供:Dev Guides
clientWidth
およびclientHeight
を使用すると、HTML要素のピクセルサイズを取得できます。 寸法は、HTML要素内のコンテンツの寸法とパディングを使用して計算されます。
注:clientWidth
およびclientHeight
の計算時に、境界線、マージン、またはスクロールバー(存在する場合)は除外されます。
clientWidthとclientHeightを使用する
<div id="foo"> Hello World </div>
const clientWidth = document.querySelector('#foo').clientWidth; const clientHeight = document.querySelector('#foo').clientHeight;
学習演習
演習として、次のHTML要素のclientWidth
およびclientHeight
の値を計算してみてください。
/********************************************** ** If the HTML element is <div id="foo"/> ** **********************************************/ const clientWidth = document.querySelector('div#foo').clientWidth; const clientHeight = document.querySelector('div#foo').clientHeight; console.log(clientWidth, clientHeight); // --> 200, 100
どのように計算されましたか? HTML要素内のコンテンツにパディングを追加し、余白と境界線を無視します。
(10 + 50) + 140 // clientWidth === 200 (30) + 70 // clientHeight === 100
別のことを試してみましょう! このHTML要素のclientWidth
とclientHeight
を計算してみてください。
(10 + 10) + 230 // clientWidth === 250 (30 + 20) + 70 // clientHeight === 120
ノート
- ブロックレベル:
clientWidth
およびclientHeight
は、インラインHTML要素(span
、em
、a
)。0
が返されます! - 丸められた値:値は最も近い整数に丸められます。 より正確な値が必要な場合は、 getBoundingClientRect()を使用してください
- 読み取り専用:新しい値を割り当ててHTML要素のサイズを変更することはできません。 たとえば、これは何もしません:
someElement.clientWidth = 30
clientWidth
およびclientHeight
は、すべての主要なデスクトップおよびモバイルブラウザーでサポートされています。
clientWidthおよびclientHeightの詳細については、公式のW3C仕様を参照してください。