hifiveのUIライブラリ紹介「ドラッグ&ドロップ」
今回はWebのUIで見かけることが多くなってきたドラッグ&ドロップを実装する方法を紹介します。hifiveではなく、jQuery UIと組み合わせた方法になります。
実際に動くデモはこちらになります。
必要なライブラリ
ドラッグ&ドロップを行う際には次のライブラリを利用します。
HTML
HTMLは次のようになります。idをドラッグできるDOM、されるDOMにそれぞれ設定しておきます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div id="container"> | |
<div id="draggable" class="ui-widget-content"> | |
<p>Drag me to my target</p> | |
</div> | |
<div id="droppable" class="ui-widget-header"> | |
<p>Drop here</p> | |
</div> | |
</div> |
JavaScript
hifiveのコントローラの基本形は次のようになります。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var controller = { | |
__name: 'Drag&DropController', | |
// 初期化処理 | |
__ready: function() { | |
}, | |
// 要素がドロップされた時のコールバック | |
drop: function(org, event, ui) { | |
} | |
}; | |
// コントローラの作成と要素へのバインド. | |
h5.core.controller('#container', controller); |
まず初期化処理を行います。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 初期化処理 | |
__ready: function() { | |
var that = this; | |
$('#draggable').draggable(); | |
$('#droppable').droppable({ | |
drop: that.ownWithOrg(that.drop) | |
}); | |
}, |
このように記述することでドラッグできるDOMが作られ、マウスでドラッグできます。droppableはドロップできるDOMで、dropされた時にコールバック処理を呼び出します。
最後にドロップされた時のコールバックを記述します。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 要素がドロップされた時のコールバック | |
drop: function(org, event, ui) { | |
$(org).addClass('ui-state-highlight').find('p').html('Dropped!'); | |
} |
CSS
CSSは次のように記述しました。これはデザインに応じて変更してください。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#draggable { | |
width: 100px; | |
height: 100px; | |
padding: 0.5em; | |
float: left; | |
margin: 10px 10px 10px 0; | |
} | |
#droppable { | |
width: 150px; | |
height: 150px; | |
padding: 0.5em; | |
float: left; | |
margin: 10px; | |
} |
これで完成です。
jQueryの記述に従っていますが、hifiveの中でコントロールできます。UIを自由に設定させたり、データを移動したりするような処理を作る際に使ってください。
今回のサンプルはこちらにあります。コードを確認する際に利用してください。
コメントは受け付けていません。