jQueryで要素の幅と高さを取得するメソッドのまとめです。まず幅ですが、対象要素の幅を取得するwidth、対象要素のpaddingを含めた幅を取得するinnerWidth、対象要素のpadding・borderを含めた幅を取得するouterWidthです。outerWidthに引数にtrueを渡すとmargin・padding・borderを含めた幅を取得します。
次に高さです。対象要素の高さを取得するheight、対象要素のpaddingを含めた高さを取得するinnerHeight、対象要素のpadding・borderを含めた高さを取得するouterHeightです。outerHeightに引数にtrueを渡すとmargin・padding・borderを含めた高さを取得します。
以下のhtmlの構造でテストします。
<div class="text">
<p>ダミーテキスト01</p>
<p>ダミーテキスト02</p>
<p>ダミーテキスト03</p>
<p>ダミーテキスト04</p>
<p>ダミーテキスト05</p>
</div>
クラス名textのdivタグのCSSは以下の通りです。
.text {
margin: 20px;
padding: 15px;
border: 5px solid #000;
}
対象要素の幅と高さを取得できる各メソッドを利用してconsole.logで出力します。
$(function() {
var result01 = $('.text').width();
var result02 = $('.text').innerWidth();
var result03 = $('.text').outerWidth();
var result04 = $('.text').outerWidth(true);
var result05 = $('.text').height();
var result06 = $('.text').innerHeight();
var result07 = $('.text').outerHeight();
var result08 = $('.text').outerHeight(true);
console.log(result01);
console.log(result02);
console.log(result03);
console.log(result04);
console.log(result05);
console.log(result06);
console.log(result07);
console.log(result08);
});
//result01
550
//result02
580
//result03
590
//result04
630
//result05
184
//result06
214
//result07
224
//result08
264
width・heightの両メソッドは引数を指定することで幅と高さが設定できます。innerWidth・outerWidth・innerHeight・outerHeightの各メソッドはいずれも値を取得するためのメソッドで、値を設定することはできません。
//width・heightメソッドのみ値の設定が可能
$(function() {
$('.text').width(400);
$('.text').height('auto');
});
width・heightの両メソッドは以下のようにWEBページ全体の幅と高さやブラウザの幅と高さを取得できます。WEBページ全体の幅とブラウザの幅は同じです。なおこの場合、innerWidth・innerHeightの両メソッドを使っても取得結果は同じです。
$(function() {
$(document).width(); //WEBページ全体の幅
$(document).height(); //WEBページ全体の高さ
$(window).width(); //ブラウザの幅
$(window).height(); //ブラウザの高さ
});





