4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jQuery UI 導入と draggable を使ってみる

Posted at

備忘録です.
jQuery UI の draggable を使って要素を自由に動かすインタラクションを試してみました.
今回,初めてjQuery UI を使うので導入とサンプルをまとめておきます.

環境

  • MacOSX (10.9)
  • jQuery UI (1.11.0)
  • jQuery (1.10.2)

jQuery UI のダウンロード

jQuery UI は,http://jqueryui.com/ からダウンロードすることが出来ます.
この記事を書いている時点(2014/07/09)では,1.11.0 が stable 版となっているので,
これをダウンロードします.
ダウンロード時には,どの機能を含めるかカスタムすることができます.
今回は,Interactions の Draggable を含めるようにカスタムしてください.

解凍したjquery-ui-1.11.0ディレクトリにはjQuery UI の簡単なサンプルを見ることができるindex.htmlや,
/external/jqueryディレクトリにはjQuery(1.10.2)が同梱されています.

jQuery UI を利用する

サンプルファイルを作成して,jQuery UI の利用の流れと要素を自由に動かすことのできる draggable を試していきます.
今回のサンプルはjquery-ui-1.11.0ディレクトリ直下に作成することを想定しています.
jQuery UI を利用する際には,下記の様にjquery-ui.cssやjquery-ui.jsなどを読み込む事になります.

sample.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <title>jquery ui test</title>
  <meta charset="utf-8">
  <link rel="stylesheet" href="./jquery-ui.css">
  <link rel="stylesheet" href="./css/style.css">
</head>
<body>
  <div id="container">

    <div id="draggableArea">
      <div id="draggable">
        <p>draggable!</p>
      </div>
    </div>

  </div>

  <script src="./external/jquery/jquery.js"></script>
  <script src="./jquery-ui.js"></script>
  <script src="./js/drag.js"></script>
</body>
</html>
style.css
body {
  width: 940px;
  height: 100%;
  margin: 0 auto;
  padding: 0;
}

div#draggableArea {
  width: 100%;
  height: 480px;
  border: solid 1px #000;
}

div#draggable {
  width: 25%;
  height: 25%;
  border: solid 1px #000;
}
drag.js
$('#draggable').draggable( {
  containment: '#draggableArea',
  scroll: false,
});

ページの中央に大きな枠とドラッグで自由に移動ができる小さな枠ができていれば完成です.
今回はdrag.jsで,要素をdraggableにする際,オプションとして containment: #draggableArea
といったように親要素を指定しています.
これを行うことによって親要素からはみ出してドラッグ出来ないようにしています.

jQuery UI を使ってフォントサイズなどを統一したものにしたい時は,
class="ui-widget"class="ui-widget-content" などを指定してあげるといいです.
詳しくは,公式の Document もしくは1.10.0のものですが,わかりやすく日本語化してくださった神様がいらっしゃるので
こちら http://js.studio-kingdom.com/ を参照するといいと思います.

ひとこと

miwaとカフェオレで書くスピード1.1倍増しになったと思ったらカフェインでトイレが近くなって効率0.1落ちた (完)

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?