jQuery を使用すれば、要素やブラウザのウィンドウの大きさの取扱いは簡単です。
jQuery には、大きさを操作するためのいくつかの重要なメソッドがあります:
width() メソッドは、要素の幅を設定または返します(padding、border、margin は含みません)。
height() メソッドは、要素の高さを設定または返します(padding、border、margin は含みません)。
次の例は、指定した <div> 要素の幅と高さを返します:
$("button").click(function(){
var txt = "";
txt += "Width: " + $("#div1").width() + "</br>";
txt += "Height: " + $("#div1").height();
$("#div1").html(txt);
});
Try it Yourself »
innerWidth() メソッドは、要素の幅を返します(padding を含みます)。
innerHeight() メソッドは、要素の高さを返します(padding を含みます)。
次の例は、指定した <div> 要素の inner-width/height を返します:
$("button").click(function(){
var txt = "";
txt += "Inner width: " + $("#div1").innerWidth() + "</br>";
txt += "Inner height: " + $("#div1").innerHeight();
$("#div1").html(txt);
});
Try it Yourself »
outerWidth() メソッドは、要素の幅を返します(padding と border を含みます)。
outerHeight() メソッドは、要素の高さを返します(padding と border を含みます)。
次の例は、指定した <div> 要素の outer-width/height を返します:
$("button").click(function(){
var txt = "";
txt += "Outer width: " + $("#div1").outerWidth() + "</br>";
txt += "Outer height: " + $("#div1").outerHeight();
$("#div1").html(txt);
});
Try it Yourself »
outerWidth(true) メソッドは、要素の幅を返します(padding、border と margin を含みます)。
outerHeight(true) メソッドは、要素の高さを返します(padding、border と margin を含みます)。
$("button").click(function(){
var txt = "";
txt += "Outer width (+margin): " + $("#div1").outerWidth(true) + "</br>";
txt += "Outer height (+margin): " + $("#div1").outerHeight(true);
$("#div1").html(txt);
});
Try it Yourself »
次の例は、文書(HTML 文書)とウィンドウ(ブラウザのビューポート)の幅と高さを返します:
$("button").click(function(){
var txt = "";
txt += "Document width/height: " + $(document).width();
txt += "x" + $(document).height() + "\n";
txt += "Window width/height: " + $(window).width();
txt += "x" + $(window).height();
alert(txt);
});
Try it Yourself »
次の例は、指定した <div> 要素の 幅と高さを設定します:
練習問題 1 » 練習問題 2 » 練習問題 3 » 練習問題 4 » 練習問題 5 »
すべての jQuery CSS メソッドの完全な概要については、jQuery HTML/CSS リファレンスをご覧ください。