jQuery 要素の幅と高さを取得する width height
今回は、jQueryの「width」,「height」について書きます。
「width」,「height」は、要素の幅と高さを取得できます。
「width」が幅で、「height」が高さです。
2つとも、このように使います。
$('#target').width(); $('#target').height();
これを使ってdivボックスの幅と高さを取得するプログラムを書いてみます。
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>jQuery</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> </head> <body> <h1>TEST</h1> <div id="target" style="width:100px; height:200px; background:red"></div> <script> $(function(){ console.log( 'w = ' + $('#target').width() ); console.log( 'h = ' + $('#target').height() ); }); </script> </body> </html>
実行結果1
実行結果2
ちゃんと取得できています。
「width」,「height」は、引数に数値を指定することもできます。
$('#target').width(300); $('#target').height(200);
数値を指定すると、要素の高さや幅を変更できます。
「.height('200px')」のように「px」で指定することも可能です。
「width」,「height」を使えば、今のウィンドウのサイズも取得できます。
$(window).width(); $(window).height();
「$(window)」とすれば、ウィンドウサイズを取得できます。
また、「$(document)」とすれば、ドキュメントサイズ、「$('body')」とすれば、bodyのサイズが取得できます。
ちなみに、リサイズ時もウィンドウサイズ取得したい場合は、こんな感じすれば大丈夫です。
$(function(){ $(window).resize(function(){ console.log( 'w = ' + $(document).width() ); console.log( 'h = ' + $('body').height() ); }); });
jqueryのresizeメソッドを使っています。
これで、終わります。
参考サイト
height() - jQuery 日本語リファレンス
width() - jQuery 日本語リファレンス