テキストボックスを作る

 需要が無くても続けます。前回はテキストボックスを作るのに

$("<div/>").css({"position": "relative", "top": "20px", "left": "30px", "width": "200px", "height": "50px", "background-color": "lime"}).appendTo("#editWindow");

CSSを直書きしてましたが、これだとみっともないのでクラスを作ってCSSを分離させます。

div.textBox {
  position: absolute;
  top: 20px;
  left: 20px;
  width: 200px;
  height: 50px;
  background-color: #e2e2e2;
}

として

#("<div/>").addClass("textBox")
           .appendTo("#editWindow");

こんな感じにしました。次にどのテキストボックスを編集中であるか識別するためにフォーカスを意味するfocusElementクラスを作りました。

div.focusElement {
  border: dotted 3px gray;
}

focusElementクラスの設定と解除には以下のコードで。

function setFocusElement(elem) {
  $(".focusElement").removeClass("focusElement");
  $(elem).addClass("focusElement");
}

function resetFocusElement() {
  $(".focusElement").removeClass("focusElement");
}

function getFocusElement() {
  return $(".focusElement");
}

これをテキストボックスに関連付けます。また作成時にフォーカスを初期設定しておきます。本当はfocus()とblur()を使いたいんだけどdiv要素では無理らしいです。

#("<div/>").addClass("textBox")
           .addClass("focusElement")
           .click(function() { setFocusElement(this); })
           .appendTo("#editWindow");

テキストボックスをドラッグ可能にするためにはjQuery UIを用いる。必要なのはui.core.jsとui.draggable.js。これを読み込んで、ドラッグ可能にさせたい要素でdraggable()を実行します。また、編集画面の外までドラッグさせたくないときはハッシュでdraggable({"containment": "#editWindow"})とします。次に、テキストボックスをリサイズ可能とするためにもjQuery UIを用いる。必要なのはui.core.jsとui.resizable.js、それとui.all.css。そしてdraggable({"containment": "#editWindow"})と同じようにresizable({"containment": "#editWindow"})します。これらをまとめたのが以下のコード。

#("<div/>").addClass("textBox")
           .addClass("focusElement")
           .click(function() { setFocusElement(this); })
           .draggable({"containment": "#editWindow"})
           .resizable({"containment": "#editWindow"})
           .appendTo("#editWindow");

簡単ですね!
http://github.com/yuribossa/qff/tree/master