【问题标题】:Swap element during drag - jquery ui拖动期间交换元素 - jquery ui
【发布时间】:2019-07-07 08:26:03
【问题描述】:

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

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/

【问题讨论】:

  • 1)我在您的示例中没有看到“红色”框 2)您不能真正做到这一点。因此,在拖动过程中,您可以使用over 回调来操作助手或可拖动元素,但最好不要更改元素本身。另外,您不是在代码中交换它们,而是将一个嵌套到另一个中。

标签: jquery drag-and-drop drag jquery-ui-draggable


【解决方案1】:

考虑如下函数:

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

看你的代码,元素都是一样的,都是&lt;div&gt;,类一样等等,唯一的区别是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/

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    相关资源
    最近更新 更多