【脱jQuery】jQuery の width, height の取得を Pure JavaScript に置き換える
jQuery は window や document 、element に対して幅 ( width
, innerWidth
, outerWidth
) と高さ ( height
, innerHeight
, outerHeight
) の取得ができる。
element に対して width や height を取得するための互換コードを紹介してる記事が多いが、 window
や document
に対しての取得について触れてる記事がなさそうだったので、調べてみた。
jQuery 3.5 をベースに調査している。
$(window)
に対しての width, height の取得
jQuery のソースコードではこの部分 https://github.com/jquery/jquery/blob/7a0a850f3d41c0412609c1d32b1e602d4afe2f4e/src/dimensions.js#L23-L29
$(window).width
document.documentElement.clientWidth
window
に対しての width
の取得なのに、いきなり document
が出てくるのでびっくりすると思うが、間違いではない。
window
には width
プロパティはなく、 innerWidth
か outerWidth
しかない。
また、window.innerWidth
は スクロールバーを含む ウィンドウのビューポートの幅を返す。
https://developer.mozilla.org/ja/docs/Web/API/Window/innerWidth
たいていの場合、取得したいのは描画が可能なエリア、つまりスクロールバーを除いた幅なので、その利用者側の意図と JavaScript の使用の差を jQuery が吸収してくれている結果。
逆に、スクロールバーを含めたウィンドウのビューポートの幅を取得したい場合は window.innerWidth
を使うことになる。
$(window).innerWidth
document.documentElement.clientWidth
$(window).innerWidth
で取得できる値は、 $(window).width
と同じである。
$(window).outerWidth
window.innerWidth
$(window).innerWidth
はスクロールバーを含めた幅が返ってくる。
window.outerWidth
はブラウザの外側の幅(サイドバーやその他ブラウザのUIを含めたもの)を返すので注意する。
$(window).height
document.documentElement.clientHeight
詳細は $(window).width
と同じで、width
を height
に読み替えれば大丈夫。
$(window).innerHeight
document.documentElement.clientHeight
$(window).innerHeight
で取得できる値は、 $(window).height
と同じである。
$(window).outerHeight
window.innerHeight
詳細は $(window).outerWidth
と同じで、width
を height
に読み替えれば大丈夫。
$(document)
に対しての width, height の取得
jQuery のソースコードではこの部分 https://github.com/jquery/jquery/blob/7a0a850f3d41c0412609c1d32b1e602d4afe2f4e/src/dimensions.js#L32-L42
$(document).width
Math.max( document.body.scrollWidth, document.documentElement.scrollWidth, document.body.offsetWidth, document.documentElement.offsetWidth, document.documentElement.clientWidth )
$(document).innerWidth
$(document).width
と同じ値を返す。
$(document).outerWidth
$(document).width
と同じ値を返す。
$(document).height
Math.max( document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight, document.documentElement.clientHeight )
$(document).innerHeight
$(document).height
と同じ値を返す。
$(document).outerHeight
$(document).height
と同じ値を返す。