オブジェクトを重ね合わせる
絶対位置指定によるオブジェクトの配置は、HTML既定のレイアウトとは異なり、イメージや文字が重なり合う可能性があります。重なり合ったオブジェクト同士は、z-indexと呼ばれるスタイル属性の順番で表示されます。z-indexスタイル属性は、styleオブジェクトのzIndexプロパティで設定することができます。
object.style.zIndex [ = vOrder ]
デフォルトでは、HTMLソース上で出現したオブジェクトの順番で重ね合わせる「auto」が設定されていますが、この順番は数値で指定することができます。数値で指定した場合、値が小さいほど背面に、大きいほど前面に表示されます。
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=shift_jis"> <title>サンプル 04</title> <script language="javascript"> function loaded() { image1.style.position = "absolute"; image2.style.position = "absolute"; image1.style.left = 10; image1.style.top = 100; image2.style.left = 70; image2.style.top = 250; } function image1_moved() { if (event.ctrlKey) { image1.style.zIndex = 1; image2.style.zIndex = 0; image1.style.left = event.x - (image1.width / 2) + "px"; image1.style.top = event.y - (image1.height / 2) + "px"; } } function image2_moved() { if (event.ctrlKey) { image2.style.zIndex = 1; image1.style.zIndex = 0; image2.style.left = event.x - (image2.width / 2) + "px"; image2.style.top = event.y - (image2.height / 2) + "px"; } } </script> </head> <body onLoad="loaded()"> <h1>サンプルプログラム 4</h1> <img src="test00.jpg" id="image1" onMouseMove="image1_moved()"> <img src="back.jpg" id="image2" onMouseMove="image2_moved()"> </body> </html>
このドキュメントを表示すると、2つのイメージが重なって表示されていることが確認できます。マウスカーソルをイメージ上に移動させて、[Ctrl]キーを押しながらカーソルを動かしてください。[Ctrl]キーを押している間は、カーソル下のイメージがカーソルの動きに合わせて移動します。このとき、移動させる対象のイメージのzIndexプロパティ値を変更して前面に表示するように仕掛けています。この機能によって、移動させているアクティブなイメージを最前面に配置することができます。前面に表示させなければならないイメージが背景のイメージに隠れるようなことがある場合は、zIndexプロパティを設定してください。
