outerWidth とは
- ここで説明する outerWidth とは次の語句からなる jQuery のメソッドです。
- outer
- 読み: アウター
意味: 外、外側 - width
- 読み: ウィズ
意味: 幅
outerWidth メソッドの概要
このメソッドはマージン領域やボーダー領域を含む要素の横幅を取得、または設定することができます。
つまり、ボーダーの左辺と右辺の横幅 + パディングの左辺と右辺の横幅 + コンテンツボックスの横幅の総和を求めたり、設定することができるということです。
またメソッドの引数に true を指定することでマージン領域の横幅も含めることができます。
構文
サンプルを見る前に構文を確認しておきます。
このメソッドの既定の引数は false です。() の中が空の場合は false の設定で横幅を求めます。
$(Selector).outerWidth([includeMargin]);
$(Selector).outerWidth(value [, includeMargin]);
$(Selector).outerWidth(function);
- includeMargin: マージン領域の横幅も含めるかどうかを true か false で指定します。この引数を省略した場合、既定値の false が選択されます。
- value: 横幅を設定する場合の設定値です。
- function: 関数の結果値を value として利用することができます。
サンプルコードと実行結果
このサンプルでは div 要素を使用しています。 対象となる div 要素には idChild の識別子を設定しています。
idChild には、あらかじめ CSS で要素のコンテンツボックスの横幅を 200px、パディングを 20px、ボーダーを 5px、マージンを 20px に設定しておき、 outerWidth(false) と outerWidth(true) で値を取得してみました。 確認のために比較する値が必要でしたので width() も使用して要素のコンテンツボックスの横幅も取得しています。
サンプルコード: CSS
<style>
#idParent{
border: thin dashed currentColor;
margin: 0;
padding: 0;
width: max-content;
}
#idChild{
border: 5px solid ##red;
background-color: ##khaki;
background-clip: content-box;
box-sizing: content-box;
margin: 20px;
padding: 20px;
width: 200px;
height: 200px;
}
</style>
- 09: border (要素の境界線: 5px)
- 13: margin (要素の外側の余白: 20px)
- 14: padding (要素の内側の余白: 20px)
- 15: width (要素の横幅: 200px ここではコンテンツボックスの横幅です。)
サンプルコード: HTML
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div id="idParent">
<div id="idChild"></div>
</div>
<output id="idWidth">innerText</output><br>
<output id="idOuterWidthFalse">innerText</output><br>
<output id="idOuterWidthTrue">innerText</output>
</body>
- 05: div要素 (親要素です。このサンプルでは特別な意味を持ちません。)
- 06: div要素 (子要素です。この要素の横幅を取得します。)
- 08: output要素 (jQuery で width() の値を出力します。)
- 09: output要素 (jQuery で outerWidth(false) の値を出力します。)
- 10: output要素 (jQuery で outerWidth(true) の値を出力します。)
サンプルコード: script
<script>
$(document).ready(function(){
$("#idWidth").text("width="+$("#idChild").width());
$("#idOuterWidthFalse").text("outerWidth(false)="+$("#idChild").outerWidth(false));
$("#idOuterWidthTrue").text("outerWidth(true)="+$("#idChild").outerWidth(true));
},false);
</script>
- 02: Docment.ready (DOMの読込みが完了した時点で関数を呼びます。)
- 03: 関数の内容 (width() の結果を idWidth に出力します。)
- 04: 関数の内容 (outerWidth(false) の結果を idOuterWidthFalse に出力します。)
- 05: 関数の内容 (outerWidth(true) の結果を idOuterWidthTrue に出力します。)
結果は要素のコンテンツボックスの横幅を CSS の box-sizing プロパティが初期値の状態のままで、 width プロパティを 200px に設定しているので、jQuery の width() メソッドで横幅を取得すれば 200 という値が返ってきています。 また、CSS で margin と padding を 20px に設定しているので、コンテンツボックスの左右には合わせて 40px の余白があり、ボーダー領域の外側にも左右合わせて 40px の余白が生成されています。 また、 border で境界線の幅を 5px に設定しているので左右のボーダー領域を合わせると 10px です。
これを outerWidth(false) で取得するとコンテンツボックスの横幅 200px とパディングの左右辺の横幅 40px とボーダーの左右辺の横幅 10px を足した 250 という値が返ってきています。 outerWidth(true) の場合は outerWidth(false) の戻り値である 250 とマージン領域の左右辺の横幅 40px を足した 290 という値が返ってきています。