使用 jQuery UI 将一个元素拖到另一个元素上时交换元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7625401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swap elements when you drag one onto another using jQuery UI
提问by James
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="dragdrop" 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.)
如何使用 jQuery UI (Draggable / Droppable) 来实现,如果一个 div 被放到另一个 div 上,它们会交换位置?(如果它被拖到其他任何地方,它会恢复到原来的位置。)
Thanks.
谢谢。
回答by satrun77
Here is an example of how you can swap elements with drag and drop http://jsfiddle.net/76yRN/1/
这是一个如何通过拖放来交换元素的示例http://jsfiddle.net/76yRN/1/
Another question about swapping elements in jquery jQuery draggable items lose their draggability after being swapped (with jsfiddle example)
关于在 jquery jQuery 可拖动项中交换元素的另一个问题在交换后失去了它们的可拖动性(以 jsfiddle 为例)
Hope this helps
希望这可以帮助
回答by hirendra
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/
您只需将元素从一个替换为另一个。前段时间我创建了一个演示,用于在 UL 列表之间交换元素。检查这个:http: //www.authorcode.com/swap-elements-when-drag-one-onto-another-using-jquery-ui/
回答by Kirk Ross
I used a combination of solutions to arrive at this, with #large_tiles and #small_tiles being two lists:
我使用了解决方案的组合来解决这个问题,#large_tiles 和 #small_tiles 是两个列表:
$(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();
}
});
}
});