将可拖动的内容限制在多个元素内

4
我为一个网站编写了一个用户脚本,其中包含了一个 jQuery UI 的 draggable。简化来说,该网站有两行,每一行都有两个水平放置的 div。
该网站布局以前使用了两个内部 div 来代替行。可拖动的内容被限制在右列的父元素中,这正是我们想要的。现在,然而,没有办法将其限制在右侧“列”中,因为该列不再存在于 DOM 中。
是否有一种方法可以流畅地将可拖动的 div 包含在 div 右列中,而无需旧的父元素?如果需要,我可以添加元素到 DOM 中(或执行任何操作),我们可以使用完整的 jQuery 和 jQuery UI 功能。我知道可以在右上角的 div 上使用 droppable,但据我所知,那样会导致可拖动的内容在两者之间捕捉。如果这是唯一的选择,那么我会这样做,但如果有其他方法,我很乐意看到它。

FIDDLE

<div id="outercontainer">
  <div id="toprow">
    <div id="topleft"></div>
    <div id="topright"></div>
  </div>
  <div id="bottomrow">
    <div id="bottomleft"></div>
    <div id="bottomright"></div>
  </div>
</div>

<div id="dragme"></div>

我不明白你想要什么。可拖动的应该只能在“topright”和“bottomright”放置,是吗? - T J
@TJ 是的,没错。我希望可拖动元素可以在右侧“列”(toprightbottomright)的任何位置使用。能够在两者之间流畅移动,即不会在两者之间捕捉,这将是理想的,尽管我明白如果这不可能的话。 - vaindil
1个回答

1
实际上,用于限制位置的包含值是一个坐标数组,它是基于您在选项中设置的对象计算出来的。但是,您可以访问可拖动实例上的此包含属性,并根据需要进行修改。唯一的限制是它必须是一个矩形,不能混合形状。
在您的情况下,您可以从元素中简单地计算出坐标。
$("#dragme").draggable({
  // You still need to set a value for containment
  // else it won't be checked when evaluating the position
  containment: 'document',
  start: function(e, ui) {
    // You simply set a left, top, right, bottom coordinates.
    // You need to set it on start so if the elements have been
    // resized, the containment follows.
    var cont = [
      $('#topleft').offset().left + $('#topleft').outerWidth(),
      $('#toprow').offset().top,
      $('#toprow').offset().left + $('#toprow').outerWidth() - ui.helper.width(),
      $('#bottomrow').offset().top + $('#bottomrow').outerHeight() - ui.helper.height(),
    ]

    $(this).draggable('instance').containment = cont;
  }
});

https://jsfiddle.net/nxxbh8eL/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接