开发者

Swap elements when you drag one onto another using jQuery UI

开发者 https://www.devze.com 2023-04-09 18:03 出处:网络
I have an arrangement of elements on a page: <div> <div class=\"dragdrop\" style=\"top:0px;left: 0px;\">1</div>

I have an arrangement of elements on a page:

<div>
  <div class="dragdrop" style="top:0px;  left: 0px;  ">1</div>
  <div class="dragdrop" style="top:40px; left: 0px;  ">2</div>
  <div class="dra开发者_如何学Gogdrop" style="top:60px; left: 0px;  ">3</div>
  <div class="dragdrop" style="top:0px;  left: 100px;">4</div>
  <div class="dragdrop" style="top:40px; left: 100px;">5</div>
  <div class="dragdrop" style="top:60px; left: 100px;">6</div>
</div>

How can I use jQuery UI (Draggable / Droppable) to make it so that if one div is dropped onto another, they swap positions? (And if it's dragged anywhere else, it reverts back to its old position.)

Thanks.


Here is an example of how you can swap elements with drag and drop http://jsfiddle.net/76yRN/1/

Another question about swapping elements in jquery jQuery draggable items lose their draggability after being swapped (with jsfiddle example)

Hope this helps


You just replace the elements from one to another. Some time ago i have created a demo for swapping elements between to UL list. check this: http://www.authorcode.com/swap-elements-when-drag-one-onto-another-using-jquery-ui/


I used a combination of solutions to arrive at this, with #large_tiles and #small_tiles being two lists:

$(function() {
$("#large_tiles li, #small_tiles li").draggable({
    zIndex: 2,
    appendTo: "body",
});

initDroppable($("#large_tiles li, #small_tiles li"));

initSwap();
function initSwap() {
    initDroppable($("#large_tiles li, #small_tiles li"));
    initDraggable($("#large_tiles li, #small_tiles li"));
}
function initDraggable($elements) {
    $elements.draggable({
        zIndex: 2,
        appendTo: "body",
        helper: "clone",
        start: function(e, ui) {
            $(ui.helper).addClass("clone");
        },
        cursorAt: { left:50, top:75 }
    });
}
function initDroppable($elements) {
    $elements.droppable({
        activeClass: "active-tile",
        hoverClass: "hover-tile",
        over: function(event, ui) {
            var $this = $(this);
        },
        drop: function(event, ui) {
            var $this = $(this);
            var linew1 = $(this).after(ui.draggable.clone());
            var linew2 = $(ui.draggable).after($(this).clone());
            $(ui.draggable).remove();
            $(this).remove();
            initSwap();
        }
    });
}
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号