Jquery draggable决定我能抓多远

Jquery draggable decide how far I can grab

我正在尝试理解 jquery 可拖动交互,我的目标是能够将文本仅向右移动 200 像素然后停止,而不是从正常位置向左移动,但如果将其拖动到右边我应该可以把它拖回左边。有没有一种聪明而简单的方法来实现这一目标?在 documentation 中找不到任何内容?

$("#drag").draggable({
  axis: "x"
});
.draggable {
  width: 90px;
  height: 90px;
  padding: 0.5em;
  float: left;
  margin: 0 10px 10px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" />

<div id="drag" class="draggable ui-widget-content">
  <p>I can be dragged only horizontally</p>
</div>

要完成这项工作,您可以使用 drag 事件。您可以检查当前位置是否在可接受的水平范围内(根据问题中的描述为 0-200 像素),然后使用 Math.max()Math.min():

禁止超出该范围的任何内容

$("#drag").draggable({
  axis: "x",
  drag: function(event, ui) {
    ui.position.left = Math.max(0, Math.min(200, ui.position.left));
  }
});
.draggable {
  width: 90px;
  height: 90px;
  padding: 0.5em;
  float: left;
  margin: 0 10px 10px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" />
<div id="drag" class="draggable ui-widget-content">
  <p>I can be dragged only horizontally</p>
</div>

最后要注意的是 jQuery 和 jQueryUI 在您的 fiddle 中的版本已经非常过时了。您需要尽快更新它们,就像我在上面的示例中所做的那样。