首页 > 解决方案 > 拖动期间交换元素 - jquery ui

问题描述

我想在拖动期间交换元素。例如,当我将红色盒子拖入带有蓝色盒子的容器中时,该容器中的蓝色盒子会变成红色盒子,而我正在拖动的红色盒子会变成蓝色盒子。那我就继续把蓝框拖走。一切都是拖动过程。

HTML:

<div class="parent">
  <div class="child" id="child1"></div>
</div>
<div class="parent">
  <div class="child" id="child2"></div>
</div>
<div class="parent">
</div>

JS:

$("document").ready(function() {
  $(".child").draggable({
    /* revert: true */
  });
  $(".parent").droppable({
    //accept: '.child',
    drop: function(event, ui) {
    },
    over: function(event, ui) {
      if ($(this).children().length > 0) {
        $(ui.draggable).html($(this).children());
      }
      $(this).html(ui.draggable);
    },
  });
});

结果不是我所期望的。你可以在这里看到演示:https ://jsfiddle.net/lion5893/845ybwLs/23/

标签: jquerydrag-and-dropdragjquery-ui-draggable

解决方案


考虑如下函数:

function dragSwap(a, b) {
  var id1 = a.attr("id");
  var id2 = b.attr("id");
  b.attr("id", id1);
  a.attr("id", id2);
}

查看您的代码,元素是相同的,两者<div>,类相同等,唯一的区别是id.

你可能有这样的事情:

over: function(event, ui) {
  if ($(this).children().length > 0 && $(this).children().length == 1) {
    var item = $(this).children().eq(0);
    var drag = ui.draggable;
    dragSwap(item, drag);
  }
}

工作示例:https ://jsfiddle.net/Twisty/y285a4bq/

希望有帮助。


推荐阅读