接続してきたブラウザの画面サイズを元にHTMLのレイアウトを調整したい場合に使用するJavaScript。
今回は、textareaを画面サイズに応じて調整したかったので、実装しました。
ブラウザ画面サイズを取得して、対象となるHTML要素のサイズを設定する...
ために必要な材料(コード)を用意していきます。
function getBrowserWidth() {
if ( window.innerWidth ) {
return window.innerWidth;
}
else if ( document.documentElement && document.documentElement.clientWidth != 0 ) {
return document.documentElement.clientWidth;
}
else if ( document.body ) {
return document.body.clientWidth;
}
return 0;
}
function getBrowserHeight() {
if ( window.innerHeight ) {
return window.innerHeight;
}
else if ( document.documentElement && document.documentElement.clientHeight != 0 ) {
return document.documentElement.clientHeight;
}
else if ( document.body ) {
return document.body.clientHeight;
}
return 0;
}
ここでは、横幅に対して 0.9 を 高さに対して 0.7 をかけることで
画面にほどよく収まるサイズを計算しています。
計算した値は、CSSスタイルとして設定します。
ここでは、*document.getElementById(“myTextArea”)* を使って
対象とするHTML要素のインスタンスを取得し
そこに、CSSスタイル設定しています。
function resizeTextArea(){
var ta=document.getElementById("myTextArea");//対象となる textarea要素にidを設置しておきます
var myw=0.9*(getBrowserWidth());//画面に収まるようにやや小さくする
var myh=0.7*(getBrowserHeight());//同上
var mycss="width:"+myw+"px;height:"+myh+"px;";
ta.style.cssText=mycss;
}
作成したJavaScriptをHTMLに組み込んで完成です。
body 要素に onload を書くのをやめて
代わりに、以下のように記述しています。
window.onload = function(){ resizeTextArea(); }
window.onresize=function(){ resizeTextArea(); }
それぞれ、ロード時とリサイズ時に resizeTextArea() メソッドが呼ばれます。
MindBoard は 直観的な操作で簡単にマインドマップを描くことができる Android タブレット用アプリです。