prototype.js (2)
2005-08-29
次は Drag and Drop のサンプル。 これは、 script.aculo.us の機能を使う。 公式サイトのサンプルはこんな感じ。
script.aculo.us では、Drag and Drop でリストの並び替えを実現する Sortableという機能と、より低レベルな Drag And Dropという機能がある。 Sortable だと細かな操作ができないので、ここでは Drag And Drop を使う。
サンプルは以下のとおり。
<html>
<head>
<title>Drag and Drop test</title>
<meta http-equiv="Content-Type" content="text/html; charset=EUC_JP" />
<script src="prototype.js" type="text/javascript"></script>
<script src="scriptaculous.js" type="text/javascript"></script>
<style tyle="text/css">
.draggable { background-color: pink; border: solid 1px #888; }
</style>
</head>
<body>
<h1>Drag and Drop test</h1>
<table border="1">
<tr>
<td id="droppable1">1 <span id="draggable1" class="draggable">draggable1</span></td>
<td id="droppable2">2 <span id="draggable2" class="draggable">draggable2</span></td>
<td id="droppable3">3 <span id="draggable3" class="draggable">draggable3</span></td>
</tr>
<tr>
<td id="droppable4">4 </td>
<td id="droppable5">5 </td>
<td id="droppable6">6 </td>
</tr>
</table>
<p>
<span id="draggable4" class="draggable">draggable4</span>
<span id="draggable5" class="draggable">draggable5</span>
<span id="draggable6" class="draggable">draggable6</span>
</p>
<script type="text/javascript" language="javascript">
for(i=1;i<=6;i++) {
new Draggable('draggable' + i, { revert:true });
}
for(i=1;i<=6;i++) {
var droppable = $('droppable' + i);
Droppables.add(droppable, {
accept: 'draggable',
onDrop: function(draggable, droppable) {
droppable.element.appendChild(draggable);
}
});
}
// -->
</script>
</body>
</html>
基本は、マウスで動かす要素のDraggableと、マウスを放す場所のDroppableを使い、Droppable の onDrop イベントに、D&Dされたときに実行したい関数を登録する。 ここでは、最初のサンプルで作った、要素を移動する関数を登録している。
onDrop の関数の引数は、「the Draggable element, and the Droppable element」だとドキュメントに書いてある。 でも実際は、第二引数は Element ではなくて Droppable が渡されているみたい。 Element にアクセスするには、サンプルのように droppable.element を使う。
ちなみに
script.aculo.us は複数の機能を持っていて、それぞれ別の .js ファイルに格納されている。 このうち、 scriptaculous.js を読み込むと、全ての .js ファイルが読み込まれるみたい。