jQuery UI拖放捕捉到中心

Sav*_*lad 2 javascript jquery drag-and-drop jquery-ui

我需要一点帮助.我需要一个蓝色圆圈,一个红色圆圈,一个蓝色方块和一个红色方块.我需要将红色圆圈拖到红色正方形的中心,将蓝色圆圈拖到蓝色正方形的中心.除非我将其拖动到正确的位置,否则它应该恢复到原始位置.

这是我到目前为止:

$("#draggable, #draggable2").draggable({
    revert: 'invalid', snap: "#droppable2"
});

$("#droppable").droppable({
    accept: '#draggable'
});

$("#droppable2").droppable({
    accept: '#draggable2',
});
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/tM7cp/269/

我无法将圆圈定位到正方形的中心,我该怎么做?

T J*_*T J 6

您可以使用jQuery Ui的position()实用方法手动将项目捕捉到droppable的中心,如下所示(我稍微改变了您的逻辑以避免重复代码和CSS):

$(".draggable").draggable({
  revert: 'invalid'
});

$(".droppable").droppable({
  accept: function(item) {
    return $(this).data("color") == item.data("color");
  },
  drop: function(event, ui) {
    var $this = $(this);
    ui.draggable.position({
      my: "center",
      at: "center",
      of: $this,
      using: function(pos) {
        $(this).animate(pos, 200, "linear");
      }
    });
  }
});
Run Code Online (Sandbox Code Playgroud)
.draggable {
  float: left;
  width: 100px;
  height: 100px;
  padding: 0.5em;
  margin: 10px 10px 10px 0;
  border: 1px solid black;
  border-radius: 50%;
}
#draggable {
  background-color: red;
}
#draggable2 {
  background-color: blue;
}
.droppable {
  padding: 0.5em;
  float: left;
  margin: 10px;
}
#droppable {
  width: 100px;
  height: 100px;
  background-color: red;
}
#droppable2 {
  width: 120px;
  height: 120px;
  background-color: blue;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<div id="draggable" class="draggable" data-color="red"></div>
<div id="draggable2" class="draggable" data-color="blue"></div>
<div id="droppable" class="droppable" data-color="red"></div>
<div id="droppable2" class="droppable" data-color="blue"></div>
Run Code Online (Sandbox Code Playgroud)