Changes between Version 16 and Version 17 of HowTo/JavaScriptTutorial


Ignore:
Timestamp:
Jul 19, 2010, 5:18:30 PM (14 years ago)
Author:
村山 俊之
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • HowTo/JavaScriptTutorial

    v16 v17  
    605605</html>
    606606}}}
     607
     608これだけでは面白くないので、もっと実践的な例を示しましょう。表示方法を設定するスタイルシートを用いれば、 HTML 要素を固定の表示位置に表示することができます。以下の HTML ファイルを見てみましょう。
     609
     610{{{
     611<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
     612<html>
     613
     614<head>
     615        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
     616        <meta http-equiv="content-style-type" content="text/css">
     617        <meta http-equiv="content-script-type" content="text/javascript">
     618        <title>absolute position sample</title>
     619</head>
     620
     621<body>
     622
     623<div style="
     624  background: #09f;
     625  border: 1px solid #000;
     626  position: absolute;
     627  left: 100px;
     628  top: 50px;
     629  width: 100px;
     630  height: 100px;">
     631</div>
     632
     633</body>
     634
     635</html>
     636}}}
     637
     638この HTML をブラウザに読み込ませると、青い矩形が画面上に表示されます。この矩形は <div> 要素ですが、 style 属性によっていくつかの表示方法が設定されています。
     639
     640{{{
     641<div style="
     642  background: #09f;
     643  border: 1px solid #000;
     644  position: absolute;
     645  left: 100px;
     646  top: 50px;
     647  width: 100px;
     648  height: 100px;">
     649</div>
     650}}}
     651
     652わかりやすさの為、 style 属性の値はスタイルのパラメータ毎に改行してありますが、 background が背景 (矩形の中の色や模様; サンプルでは色のみ指定)、border が枠線の表示方法を指定するパラメータです。ポイントはその次の行からで、
     653
     654{{{
     655  position: absolute;
     656}}}
     657
     658と書くことによって、その次の 2行、すなわち left や top パラメータを用いてその要素の表示位置を座標で指定してあげることができるようになります。 width と height はそれぞれ、矩形の幅と高さです。
     659
     660DOM を用いると、このスタイルシートをパラメータ毎に変更することができるようになります。ということは、この矩形の表示位置を動かしたり、色や大きさを変えたりすることができる、ということです。試しに、ボタンを押すと矩形が右に動くだけの、簡単なプログラムを作ってみましょう。
     661
     662まず、動かしたい矩形 <div> 要素のオブジェクトを取得します。あらかじめ HTML に <div> 要素を書いておいて document.getElementById() してもよいですが、せっかくなので document.createElement() を用いて 1から作るようにしてみましょう。
     663
     664{{{
     665// 最初の表示位置、大きさ
     666var pos_x = 0;
     667var pos_y = 50;
     668var rect_width = 100;
     669var rect_height = 100;
     670
     671// 生成した <div> 要素のオブジェクトを入れておく変数
     672var div;
     673
     674// HTML の読み込みが終わったら実行されるハンドラ
     675window.onload = function() {
     676  // <div> 要素を作成する
     677  div = document.createElement("div");
     678}}}
     679
     680<div> の生成は window.onload() メッセージハンドラ内で行います。 window.onload() は HTML 文書の読み込みが完了したときに呼び出されます。そうすると、 HTML 文書に含まれる全ての HTML 要素に DOM としてアクセスすることができます。例えば <body> 要素にも document.body プロパティとしてアクセスできるので、ここで生成した <div> 要素を、あとで
     681
     682{{{
     683  document.body.appendChild(div);
     684}}}
     685
     686と書いてやれば、<body> 要素内に、新たに作った <div> 要素を追加することができるのです。
     687
     688window.onload() メッセージハンドラより手前で、変数をいくつか定義しています。これらは、後で矩形の表示位置を変更する際に、役に立つものです。
     689
     690次に、この <div> 要素にスタイルを設定します。 DOM を用いる場合、 <div> 要素のスタイルは、 div.style プロパティにオブジェクトとして用意されていますので、以下のようにしてスタイルを設定してやることができます。
     691
     692{{{
     693  // <div> 要素のスタイルを設定する
     694  div.style.background = "#09f";
     695  div.style.border = "1px solid #000";
     696  div.style.position = "absolute";
     697  div.style.left = pos_x + "px";
     698  div.style.top = pos_y + "px";
     699  div.style.width = rect_width + "px";
     700  div.style.height = rect_height + "px";
     701}}}
     702
     703スタイルシートのパラメータの名前と、 style オブジェクトが持つプロパティの名前はだいたい同じだと思ってよいでしょう。但し、 background ではなく background-color を指定したい場合、 style オブジェクトのプロパティの名前は backgroundColor といったように、ハイフン "-" で繋がれた次のアルファベットを大文字にした名前となります。
     704
     705ちなみにこの部分は、 !JavaScript の '''with''' という構文を用いることで、以下のようにもう少しすっきり書くことができます。もっとも、これは好みの分かれる書き方ですが…。
     706
     707{{{
     708  // <div> 要素のスタイルを設定する
     709  with (div.style) {
     710    background = "#09f";
     711    border = "1px solid #000";
     712    position = "absolute";
     713    left = pos_x + "px";
     714    top = pos_y + "px"
     715    width = rect_width + "px";
     716    height = rect_height + "px";
     717  }
     718}}}
     719
     720<div> 要素の準備はできたので、 <body> 要素にこの <div> 要素を突っ込んでやります。 window.onload() でやる作業はここまでです。
     721
     722{{{
     723  document.body.appendChild(div);
     724}
     725}}}
     726
     727そして、ボタンが押されたときに呼び出される関数 moveRectangle() を実装します。この関数は、矩形の水平位置を、矩形の幅の半分ずつ右に動かす、というものです。
     728
     729{{{
     730// 矩形を右に動かす
     731function moveRectangle() {
     732  pos_x += rect_width / 2;
     733  div.style.left = pos_x + "px";
     734}
     735}}}
     736
     737pox_x や rect_width といった変数を用意しておいたのは、 div.style.left プロパティ自体は直接足し算ができない文字列だからです。また、変数 div も、この <div> 要素にいちいち ID 名を設定し、あとで document.getElementById() で取得するのが面倒だったので用意しておいたのでした。
     738
     739サンプルプログラムの全体像を以下に示します。
     740
     741{{{
     742<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
     743<html>
     744
     745<head>
     746    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
     747    <meta http-equiv="content-style-type" content="text/css">
     748    <meta http-equiv="content-script-type" content="text/javascript">
     749    <title>moving rectangle sample 1</title>
     750    <script type="text/javascript" language="JavaScript"><!--
     751// 最初の表示位置、大きさ
     752var pos_x = 0;
     753var pos_y = 50;
     754var rect_width = 100;
     755var rect_height = 100;
     756
     757// 生成した <div> 要素のオブジェクトを入れておく変数
     758var div;
     759
     760// HTML の読み込みが終わったら実行されるハンドラ
     761window.onload = function() {
     762  // <div> 要素を作成する
     763  div = document.createElement("div");
     764  // <div> 要素のスタイルを設定する
     765  with (div.style) {
     766    background = "#09f";
     767    border = "1px solid #000";
     768    position = "absolute";
     769    left = pos_x + "px";
     770    top = pos_y + "px"
     771    width = rect_width + "px";
     772    height = rect_height + "px";
     773  }
     774  document.body.appendChild(div);
     775}
     776
     777// 矩形を右に動かす
     778function moveRectangle() {
     779  pos_x += rect_width / 2;
     780  div.style.left = pos_x + "px";
     781}
     782    //--></script>
     783</head>
     784
     785<body>
     786
     787<form>
     788  <input type="button" value="click!" onclick="moveRectangle();">
     789</form>
     790
     791</body>
     792
     793</html>
     794}}}
     795
     796いかがですか? ここまでくると、なんだかいろいろなことに応用できそうな気がしてくるでしょう?
     797
     798最後に、これのさらなる応用例を 2つ程お見せしましょう。まず 1つ目は、タイマーを用いて矩形が勝手に動き続けるサンプルです。
     799
     800{{{
     801<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
     802<html>
     803
     804<head>
     805    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
     806    <meta http-equiv="content-style-type" content="text/css">
     807    <meta http-equiv="content-script-type" content="text/javascript">
     808    <title>moving rectangle sample 2</title>
     809    <script type="text/javascript" language="JavaScript"><!--
     810// 移動量 (制限値)
     811var MAX_MOVE_TIME = 8;
     812
     813// タイマーのウェイト (ミリ秒)
     814var TIMER_WAIT = 125;
     815
     816// 移動方向を表す定数オブジェクト
     817var Direction = {
     818  "RIGHT": 0,
     819  "BOTTOM": 1,
     820  "LEFT": 2,
     821  "TOP": 3
     822};
     823
     824// 表示位置、大きさ
     825var pos_x = 0;
     826var pos_y = 0;
     827var rect_width = 100;
     828var rect_height = 100;
     829
     830// 移動方向、カウント
     831var direction = Direction.RIGHT;
     832var count = 0;
     833
     834// 生成した <div> 要素のオブジェクトを入れておく変数
     835var div;
     836
     837// タイマーオブジェクトを入れておく変数
     838var timer;
     839
     840window.onload = function() {
     841  div = document.createElement("div");
     842  with (div.style) {
     843    background = "#09f";
     844    border = "1px solid #000";
     845    position = "absolute";
     846    left = pos_x + "px";
     847    top = pos_y + "px"
     848    width = rect_width + "px";
     849    height = rect_height + "px";
     850  }
     851  document.body.appendChild(div);
     852 
     853  // タイマーを設定する
     854  timer = setInterval(moveRectangle, TIMER_WAIT);
     855}
     856
     857// 矩形を動かす
     858function moveRectangle() {
     859  // 矩形の位置を変更
     860  switch (direction) {
     861    case Direction.RIGHT:   pos_x += rect_width / 2; break;
     862    case Direction.BOTTOM:  pos_y += rect_height / 2; break;
     863    case Direction.LEFT:    pos_x -= rect_width / 2; break;
     864    case Direction.TOP:     pos_y -= rect_height / 2; break;
     865  }
     866  div.style.left = pos_x + "px";
     867  div.style.top = pos_y + "px";
     868 
     869  // 方向転換
     870  if (++count >= MAX_MOVE_TIME) {
     871    direction = (direction + 1) % 4;
     872    count = 0;
     873  }
     874}
     875    //--></script>
     876</head>
     877
     878<body>
     879</body>
     880
     881</html>
     882}}}
     883
     884このサンプルでは、矩形は右だけでなく、下、左、上にも移動し、際限なく回転をし続けます。 window.setInterval() メソッドを用いることで、このように、一定の時間間隔で処理を繰り返すプログラムを作ることができます。
     885
     886もう 1つは、矩形をマウス操作のドラッグ&ドロップで動かすことができる、というものです。
     887
     888{{{
     889<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
     890<html>
     891
     892<head>
     893    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
     894    <meta http-equiv="content-style-type" content="text/css">
     895    <meta http-equiv="content-script-type" content="text/javascript">
     896    <title>moving rectangle sample 3</title>
     897    <script type="text/javascript" language="JavaScript"><!--
     898// 表示位置、大きさ
     899var pos_x = 0;
     900var pos_y = 0;
     901var rect_width = 100;
     902var rect_height = 100;
     903
     904// マウスを動かし始めた位置
     905var mouse_pos_start_x;
     906var mouse_pos_start_y;
     907var pos_start_x;
     908var pos_start_y;
     909
     910// 生成した <div> 要素のオブジェクトを入れておく変数
     911var div;
     912
     913window.onload = function() {
     914  div = document.createElement("div");
     915  with (div.style) {
     916    background = "#09f";
     917    border = "1px solid #000";
     918    position = "absolute";
     919    left = pos_x + "px";
     920    top = pos_y + "px"
     921    width = rect_width + "px";
     922    height = rect_height + "px";
     923  }
     924  div.onmousedown = startMoveRectangle;
     925  document.body.appendChild(div);
     926}
     927
     928// マウスの位置を取得する
     929function getMousePos(ev) {
     930  var pos = {};
     931  if (window.event) {   // IE の場合
     932    ev = window.event;
     933    var scroll_x = document.documentElement.scrollLeft || document.body.scrollLeft;
     934    var scroll_y = document.documentElement.scrollTop || document.body.scrollTop;
     935    pos.x = scroll_x + ev.clientX;
     936    pos.y = scroll_y + ev.clientY;
     937  }
     938  else {    // それ以外の場合
     939    pos.x = ev.pageX;
     940    pos.y = ev.pageY;
     941  }
     942  return pos;
     943}
     944
     945// 矩形を動かし始める
     946function startMoveRectangle(ev) {
     947  // 動かしはじめのマウスの位置を記憶しておく
     948  var pos = getMousePos(ev);
     949  mouse_pos_start_x = pos.x;
     950  mouse_pos_start_y = pos.y;
     951  pos_start_x = pos_x;
     952  pos_start_y = pos_y;
     953  // ドキュメント全体に、マウスを動かした場合、マウスボタンを放した場合の処理を設定する
     954  document.onmousemove = moveRectangle;
     955  document.onmouseup = endMoveRectangle;
     956 
     957  return false; // Firefox、 Opera でテキストの選択を禁止する
     958}
     959
     960// 矩形を動かす
     961function moveRectangle(ev) {
     962  // 矩形の位置を変更
     963  var pos = getMousePos(ev);
     964  pos_x = pos_start_x + pos.x - mouse_pos_start_x;
     965  pos_y = pos_start_y + pos.y - mouse_pos_start_y;
     966  div.style.left = pos_x + "px";
     967  div.style.top = pos_y + "px";
     968 
     969  return false; // IE でテキストの選択を禁止する
     970}
     971
     972// 矩形を動かし終える
     973function endMoveRectangle(ev) {
     974  moveRectangle(ev);
     975  document.onmousemove = document.onmouseup = function() { };
     976}
     977    //--></script>
     978</head>
     979
     980<body>
     981</body>
     982
     983</html>
     984}}}
     985
     986ブラウザ依存の部分もあるので若干わかりにくくなっていますが、ハンドラメソッドに渡されるイベントオブジェクトからマウスの位置を取得し、それを元に矩形の位置を移動する、という実装になっています。これをさらに応用すると、 Web ページ内でウィンドウを表示したり、ドラッグ&ドロップを表現したりすることができるようになり、 Web アプリケーションの幅が広がります。
     987