先日の続編.要素をドラッグドロップするとき,要素がすでにある場合にはスワップできる.
※要jQuery.
<script> const allowDrop = (event) => { event.preventDefault(); } const drag = (event) => { event.dataTransfer.setData('target_id', event.target.id); } const drop = (event) => { event.preventDefault(); let drop_target = event.target; let drag_target_id = event.dataTransfer.getData('target_id'); let drag_target = $('#' + drag_target_id)[0]; let tmp = document.createElement('span'); tmp.className='hide'; drop_target.before(tmp); drag_target.before(drop_target); tmp.replaceWith(drag_target); } </script>
<style> #room, #ground { width: 400px; height: 200px; display: grid; grid-template-columns: repeat(auto-fill, 100px); grid-template-rows: repeat(auto-fill, 100px); } .seat { width: 100px; height: 100px; background: #aaa; } .child { width: 100px; height: 100px; background: skyblue; } </style>
<body> <div id="ground"> <div id="child1" class="child" draggable="true" ondragstart="drag(event)" ondragover="allowDrop(event)" ondrop="drop(event)">child1</div> <div id="child2" class="child" draggable="true" ondragstart="drag(event)" ondragover="allowDrop(event)" ondrop="drop(event)">child2</div> <div id="child3" class="child" draggable="true" ondragstart="drag(event)" ondragover="allowDrop(event)" ondrop="drop(event)">child3</div> <div id="child4" class="child" draggable="true" ondragstart="drag(event)" ondragover="allowDrop(event)" ondrop="drop(event)">child4</div> </div> <br> <div id="room"> <div id="seat1" class="seat" draggable="true" ondragstart="drag(event)" ondragover="allowDrop(event)" ondrop="drop(event)">seat1</div> <div id="seat2" class="seat" draggable="true" ondragstart="drag(event)" ondragover="allowDrop(event)" ondrop="drop(event)">seat2</div> <div id="seat3" class="seat" draggable="true" ondragstart="drag(event)" ondragover="allowDrop(event)" ondrop="drop(event)">seat3</div> <div id="seat4" class="seat" draggable="true" ondragstart="drag(event)" ondragover="allowDrop(event)" ondrop="drop(event)">seat4</div> </div> </body>
child1child2child3child4
seat1seat2seat3seat4
なお,要素の上に要素を重ねたくないときは,dragover
イベントとdrop
イベントを禁止すると,ドラッグ要素が元の位置に戻る.
<script> $(function () { $('.child').on('drop dragover', function (ev) { ev.stopPropagation(); ev.preventDefault(); }); }); </script>