LoginSignup
19
17

More than 5 years have passed since last update.

jQueryによるDOMのサイズ取得と計算

Last updated at Posted at 2015-07-30

jQueryのDOMのサイズ取得は横と高さとで4種類ずつ用意されている。
考えるの面倒なときの覚え書き。

  • width() / height()
  • innerWidth() / innerHeight()
  • outerWidth() / outerHeight()
  • outerWidth(true) outerHeight(true)

width() / height()

コンテンツサイズを取得する。
つまり、padding, border, margin全部無視!

innerWidth() / innerHeight()

コンテンツサイズとpaddingを合わせた値

outerWidth() / outerHeight()

コンテンツサイズとpaddingとborderを合わせた値

outerWidth(true) / outerHeight(true)

コンテンツサイズとpaddingとborderとmarginを合わせた値。
つまり、全部載せ。

応用編?

注意事項として、左右、上下、それぞれの合算値しか取得できない。
同じ値なら半分にするだけだが、違う値の場合にそれぞれの値を取得するのは無理。

marginサイズ

var marginWidth = $dom.outerWidth(true) - $dom.outerWidth();
var marginHeight = $dom.outerHeight(true) - $dom.outerHeight();

paddingサイズ

var paddingWidth = $dom.innerWidth() - $dom.width();
var paddingHeight = $dom.innerHeight() - $dom.height();

borderサイズ

var borderWidth = $dom.outerWidth() - $dom.innerWidth();
var borderHeight = $dom.outerHeight() - $dom.innerHeight();

otherサイズ(margin + padding + border)

var otherWidth = $dom.outerWidth(true) - $dom.width();
var otherHeight = $dom.outerHeight(true) - $dom.height();

用途(何に使ったか)

基本的にjQueryでゴリゴリDOM操作をするときに使います。

material design ligntとjQuery UIを入れた時に、material design ligntのlayoutを利用しているとjQuery UIのWidgetがabsoluteなのにfixedの様な動きになる。

原因はWidgetのappend先がdefaultでbodyであることと、material design ligntでスクロールしているのはmainタグで、bodyのスクロールがoffになっているから。

jQuery UIのWidgetの追加先をappendToオプションでmain以下にして、Widgetのpositionをrelativeにすることで、コンテンツのスクロールに連動して動く様になる。

その代わりとして、jQuery UIが計算して配置しているサイズ等がずれるので、表示のタイミングで再計算させるとかってやりました。

19
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
17