会員登録(無料)
ログイン
スキルアップは今すぐこちら!▶

【jQuery】ドラッグ&ドロップでページ内の画像を動かす方法(要素をドラッグアンドドロップ移動)

jQuery(ジェイクエリ)
この記事は約3分で読めます。

前回は「JavaScriptを使ってドラッグアンドドロップでページ内の画像を移動させる」という話を書きましたが、今回は「jQuery」を使ってドラッグアンドドロップを実現してみます。

▶サンプルページはこちら

サンプル

CDNで jQuery をインポートする

まずは、前回と同じように jQueryをインポートします。

<script type="text/javascript" src="https://code.jquery.com/jquery-1.6.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>

jQueryの.draggable()を使う

.draggable()を使います。

Draggable
指定した要素をマウスで移動できるようにします。

https://js.studio-kingdom.com/jqueryui/interactions/draggable
<script>
$(document).ready(function () {
$(".img001").draggable();
});
</script>

これだけで、画像(クラス)をドラッグアンドドロップさせることができるようになりました!便利です!

図形などの範囲内でのみ画像を動かせるようにする

「Draggable Widget」を使ってみます。

Draggable Widget
Description: Allow elements to be moved using the mouse.

https://api.jqueryui.com/draggable/

containment: “#div_containment”

といった指定をすることで、要素内に限定して稼働させることができるようです。

jquery draggable - containment
I have a little project I'm working on, and have an interesting containment issue using jquery's draggable: Basically, I have two divs - a top & and a bott...
$(document).ready(function () {
$(".img002").draggable({ containment: "#range" });
});

できました!たしかに要素の範囲内でのみ画像が移動できるように限定されました。ちなみにcontainmentは「封じ込め」という意味があるようです。なるほど。

まとめ

JavaScriptで数行のコードで作っていたものがjQueryだとわずが1~2行で出来てしまう…という便利さがあります。jQuery便利ですね😃

ご参考ください😃

タイトルとURLをコピーしました