在偏移之间获得最小距离的最佳方法

时间:2018-01-03 16:37:53

标签: javascript jquery algorithm jquery-ui

我正在制作一个可拖动的文本,它应该插入一个输入,具体取决于输入之间的距离和拖动文本的最终位置,参见示例:

$('span').draggable({
opacity: 0.7,
helper: "clone",
stop: function(){
            var offset = $('.ui-draggable-dragging').offset();
            var xFinalPos = offset.left;
            var yFinalPos = offset.top;
            
        }
})
 span {
  background-color: red;
  cursor: pointer
}
div {
  margin-top:50px;
  margin-left:100px;
}
input {
  margin:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<span class="ui-draggable ui-draggable-handle">Text</span>
<div>
<input id="input1" type="text">
<input id="input2" type="text">
<input id="input3" type="text">
<input id="input4" type="text">
<input id="input5" type="text">
<input id="input6" type="text">
</div>

到目前为止,我所做的是获取拖动文本xFinalPos和yFinalPos的最终位置,我的问题是获得偏移之间最小距离的最佳方法是什么。我的最终目标是在最近的输入上打印拖动的文本。

1 个答案:

答案 0 :(得分:2)

你不需要计算距离。 jQuery UI已经为你做了:

&#13;
&#13;
$('#draggable').draggable({
  opacity: 0.7,
  helper: "clone"
});

$( ".input-grid" ).droppable({
  accept: "#draggable",
  tolerance: "intersect",
  classes: {
    "ui-droppable-hover": "active"
  },
  drop: function( event, ui ) {
    $("input", this).val($(ui.helper).text());
  }
});
&#13;
span {
  background-color: red;
  cursor: pointer
}
.content {
  margin-top:50px;
  margin-left:50px;
}
.input-grid {
  display: inline-block;
  padding: 20px;
}
.input-grid.active > input {
  border-color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<span id="draggable" class="ui-draggable ui-draggable-handle">Text</span>
<div class="content">
  <div class="input-grid">
    <input id="input1" class="dock" type="text">
  </div>
  <div class="input-grid">
    <input id="input2" class="dock" type="text">
  </div>
  <div class="input-grid">
    <input id="input3" class="dock" type="text">
  </div>
  <div class="input-grid">
    <input id="input4" class="dock" type="text">
  </div>
  <div class="input-grid">
    <input id="input5" class="dock" type="text">
  </div>
  <div class="input-grid">
    <input id="input6" class="dock" type="text">
  </div>
</div>
&#13;
&#13;
&#13;